Mock dependency in jest with typescript

前端 未结 9 1055
梦谈多话
梦谈多话 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:46

    Here's what I did with jest@24.8.0 and ts-jest@24.0.2:

    source:

    class OAuth {
    
      static isLogIn() {
        // return true/false;
      }
    
      static getOAuthService() {
        // ...
      }
    }
    

    test:

    import { OAuth } from '../src/to/the/OAuth'
    
    jest.mock('../src/utils/OAuth', () => ({
      OAuth: class {
        public static getOAuthService() {
          return {
            getAuthorizationUrl() {
              return '';
            }
          };
        }
      }
    }));
    
    describe('createMeeting', () => {
      test('should call conferenceLoginBuild when not login', () => {
        OAuth.isLogIn = jest.fn().mockImplementationOnce(() => {
          return false;
        });
    
        // Other tests
      });
    });
    

    This is how to mock a non-default class and it's static methods:

    jest.mock('../src/to/the/OAuth', () => ({
      OAuth: class {
        public static getOAuthService() {
          return {
            getAuthorizationUrl() {
              return '';
            }
          };
        }
      }
    }));
    

    Here should be some type conversion from the type of your class to jest.MockedClass or something like that. But it always ends up with errors. So I just used it directly, and it worked.

    test('Some test', () => {
      OAuth.isLogIn = jest.fn().mockImplementationOnce(() => {
        return false;
      });
    });
    

    But, if it's a function, you can mock it and do the type conversation.

    jest.mock('../src/to/the/Conference', () => ({
      conferenceSuccessDataBuild: jest.fn(),
      conferenceLoginBuild: jest.fn()
    }));
    const mockedConferenceLoginBuild = conferenceLoginBuild as 
    jest.MockedFunction<
      typeof conferenceLoginBuild
    >;
    const mockedConferenceSuccessDataBuild = conferenceSuccessDataBuild as 
    jest.MockedFunction<
      typeof conferenceSuccessDataBuild
    >;
    

提交回复
热议问题