How to change mock implementation on a per single test basis [Jestjs]

前端 未结 3 1928
太阳男子
太阳男子 2020-12-12 12:42

I\'d like to change the implementation of a mocked dependency on a per single test basis by extending the default mock\'s

3条回答
  •  再見小時候
    2020-12-12 12:56

    Vanilla JS

    Use mockFn.mockImplementation(fn).

    import { funcToMock } from './somewhere';
    jest.mock('./somewhere');
    
    beforeEach(() => {
      funcToMock.mockImplementation(() => { /* default implementation */ });
    });
    
    test('case that needs a different implementation of funcToMock', () => {
      funcToMock.mockImplementation(() => { /* implementation specific to this test */ });
      // ...
    });
    

    TypeScript

    In addition to the Vanilla JS solution:

    To prevent the message mockImplementation is not a property of funcToMock, you will need to specify the type, e.g. by changing the top line from above to the following:

    import { (funcToMock as jest.Mock) } from './somewhere';
    

    A question addressing this issue can be found here: jest typescript property mock does not exist on type

提交回复
热议问题