Jest unit test for a debounce function

前端 未结 4 2106
萌比男神i
萌比男神i 2021-02-13 22:30

I am trying to write a unit test for a debounce function. I\'m having a hard time thinking about it.

This is the code:



        
4条回答
  •  半阙折子戏
    2021-02-13 23:08

    I like this similar version easier to have failing:

    jest.useFakeTimers();
    test('execute just once', () => {
        const func = jest.fn();
        const debouncedFunc = debounce(func, 500);
    
        // Execute for the first time
        debouncedFunc();
    
        // Move on the timer
        jest.advanceTimersByTime(250);
        // try to execute a 2nd time
        debouncedFunc();
    
        // Fast-forward time
        jest.runAllTimers();
    
        expect(func).toBeCalledTimes(1);
    });
    

提交回复
热议问题