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

前端 未结 3 1926
太阳男子
太阳男子 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:47

    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

提交回复
热议问题