Jest unit test for a debounce function

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

    If in your code you are doing so:

    import debounce from 'lodash/debounce';
    
    myFunc = debounce(myFunc, 300);
    

    and you want to test the function myFunc or a function calling it, then in your test you can mock the implementation of debounce using jest to make it just return your function:

    import debounce from 'lodash/debounce';
    
    // Tell Jest to mock this import
    jest.mock('lodash/debounce');
    
    it('my test', () => {
        // ...
        debounce.mockImplementation(fn => fn); // Assign the import a new implementation. In this case it's to execute the function given to you
        // ...
    });
    

    Source: https://gist.github.com/apieceofbart/d28690d52c46848c39d904ce8968bb27

提交回复
热议问题