How to mock callback functions with jest

前端 未结 2 1320
无人共我
无人共我 2021-02-20 14:48

I\'m trying to mock a custom function with jest but I\'m having problems with it.

This is my function:

export const resizeImage = (file, fileName, callba         


        
2条回答
  •  醉话见心
    2021-02-20 15:16

    Make sure when you call the actual function by passing the callback function as one of the arguments, that function is being called from inside the test block like below

    function forEach(items, callback) {
      for (let index = 0; index < items.length; index++) {
        callback(items[index]);
      }
    }
    const mockCallback = jest.fn((x) => x + 1);
    
    test("fn", () => {
      forEach([0, 1, 2], mockCallback);
      expect(mockCallback.mock.calls.length).toBe(3);
    });
    

    And not like below

    function forEach(items, callback) {
          for (let index = 0; index < items.length; index++) {
            callback(items[index]);
          }
        }
    const mockCallback = jest.fn((x) => x + 1);
    forEach([0, 1, 2], mockCallback);
        
    test("fn", () => {
       expect(mockCallback.mock.calls.length).toBe(3);
    });
    

提交回复
热议问题