Mock dependency in jest with typescript

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

    You can use type casting and your test.ts should look like this:

    import * as dep from '../dependency';
    jest.mock('../dependency');
    
    const mockedDependency = >dep.default;
    
    it('should do what I need', () => {
      //this throws ts error
      // Property mockReturnValueOnce does not exist on type (name: string)....
      mockedDependency.mockReturnValueOnce('return');
    });
    

    TS transpiler is not aware that jest.mock('../dependency'); changes type of dep thus you have to use type casting. As imported dep is not a type definition you have to get its type with typeof dep.default.

    Here are some other useful patterns I've found during my work with Jest and TS

    When imported element is a class then you don't have to use typeof for example:

    import { SomeClass } from './SomeClass';
    
    jest.mock('./SomeClass');
    
    const mockedClass = >SomeClass;
    

    This solution is also useful when you have to mock some node native modules:

    import { existsSync } from 'fs';
    
    jest.mock('fs');
    
    const mockedExistsSync = >existsSync;
    

    In case you don't want to use jest automatic mock and prefer create manual one

    import TestedClass from './TestedClass';
    import TestedClassDependency from './TestedClassDependency';
    
    const testedClassDependencyMock = jest.fn(() => ({
      // implementation
    }));
    
    it('Should throw an error when calling playSomethingCool', () => {
      const testedClass = new TestedClass(testedClassDependencyMock());
    });
    

    testedClassDependencyMock() creates mocked object instance TestedClassDependency can be either class or type or interface

提交回复
热议问题