Jest unit test for a debounce function

前端 未结 4 2021
萌比男神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:06

    Actually, you don't need to use Sinon to test debounces. Jest can mock all timers in JavaScript code.

    Check out following code (it's TypeScript, but you can easily translate it to JavaScript):

    import * as _ from 'lodash';
    
    // Tell Jest to mock all timeout functions
    jest.useFakeTimers();
    
    describe('debounce', () => {
    
        let func: jest.Mock;
        let debouncedFunc: Function;
    
        beforeEach(() => {
            func = jest.fn();
            debouncedFunc = _.debounce(func, 1000);
        });
    
        test('execute just once', () => {
            for (let i = 0; i < 100; i++) {
                debouncedFunc();
            }
    
            // Fast-forward time
            jest.runAllTimers();
    
            expect(func).toBeCalledTimes(1);
        });
    });
    

    More information: Timer Mocks

提交回复
热议问题