Mock dependency in jest with typescript

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

    Use the mocked helper from ts-jest like explained here

    // foo.spec.ts
    import { mocked } from 'ts-jest/utils'
    import { foo } from './foo'
    jest.mock('./foo')
    
    // here the whole foo var is mocked deeply
    const mockedFoo = mocked(foo, true)
    
    test('deep', () => {
      // there will be no TS error here, and you'll have completion in modern IDEs
      mockedFoo.a.b.c.hello('me')
      // same here
      expect(mockedFoo.a.b.c.hello.mock.calls).toHaveLength(1)
    })
    
    test('direct', () => {
      foo.name()
      // here only foo.name is mocked (or its methods if it's an object)
      expect(mocked(foo.name).mock.calls).toHaveLength(1)
    })
    

    and if

    • you use tslint
    • ts-jest is in your dev-dependencies,

    add this rule to your tslint.json: "no-implicit-dependencies": [true, "dev"]

提交回复
热议问题