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

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


A nice pattern for writing test is to create a setup factory function that returns the data you need for testing the current module.

Below is some sample code following your second example although allows the provision of default and override values in a reusable way.

const spyReturns = returnValue => jest.fn(() => returnValue);describe("scenario", () => {  const setup = (mockOverrides) => {    const mockedFunctions =  {      a: spyReturns(true),      b: spyReturns(true),      ...mockOverrides    }    return {      mockedModule: jest.doMock('../myModule', () => mockedFunctions)    }  }  it("should return true for module a", () => {    const { mockedModule } = setup();    expect(mockedModule.a()).toEqual(true)  });  it("should return override for module a", () => {    const EXPECTED_VALUE = "override"    const { mockedModule } = setup({ a: spyReturns(EXPECTED_VALUE)});    expect(mockedModule.a()).toEqual(EXPECTED_VALUE)  });});


Use mockFn.mockImplementation(fn).

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


Little late to the party, but if someone else is having issues with this.

We use TypeScript, ES6 and babel for react-native development.

We usually mock external NPM modules in the root __mocks__ directory.

I wanted to override a specific function of a module in the Auth class of aws-amplify for a specific test.

    import { Auth } from 'aws-amplify';    import GetJwtToken from './GetJwtToken';    ...    it('When idToken should return "123"', async () => {      const spy = jest.spyOn(Auth, 'currentSession').mockImplementation(() => ({        getIdToken: () => ({          getJwtToken: () => '123',        }),      }));      const result = await GetJwtToken();      expect(result).toBe('123');      spy.mockRestore();    });

Gist:https://gist.github.com/thomashagstrom/e5bffe6c3e3acec592201b6892226af2

Tutorial:https://medium.com/p/b4ac52a005d#19c5