Mock dependency in jest with typescript

前端 未结 9 1073
梦谈多话
梦谈多话 2020-12-07 12:03

When testing a module that has a dependency in a different file. When assigning that module to be jest.Mock typescript gives an error that the method mock

9条回答
  •  半阙折子戏
    2020-12-07 12:44

    There are two solutions, both are casting desired function

    1) Use jest.MockedFunction

    import * as dep from './dependency';
    
    jest.mock('./dependency');
    
    const mockMyFunction = dep.myFunction as jest.MockedFunction;
    

    2) Use jest.Mock

    import * as dep from './dependency';
    
    jest.mock('./dependency');
    
    const mockMyFunction = dep.default as jest.Mock;
    

    There is no difference between these two solutions. The second one is shorter and I would therefore suggest using that one.

    Both casting solutions allows to call any jest mock function on mockMyFunction like mockReturnValue or mockResolvedValue https://jestjs.io/docs/en/mock-function-api.html

    mockMyFunction.mockReturnValue('value');
    

    mockMyFunction can be used normally for expect

    expect(mockMyFunction).toHaveBeenCalledTimes(1);
    

提交回复
热议问题