Mock dependency in jest with typescript

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

    Use as jest.Mock and nothing else

    The most concise way of mocking a module exported as default in ts-jest that I can think of really boils down to casting the module as jest.Mock.

    Code:

    import myDep from '../dependency' // No `* as` here
    
    jest.mock('../dependency')
    
    it('does what I need', () => {
      // Only diff with pure JavaScript is the presence of `as jest.Mock`
      (myDep as jest.Mock).mockReturnValueOnce('return')
    
      // Call function that calls the mocked module here
    
      // Notice there's no reference to `.default` below
      expect(myDep).toHaveBeenCalled()
    })
    

    Benefits:

    • does not require referring to the default property anywhere in the test code - you reference the actual exported function name instead,
    • you can use the same technique for mocking named exports,
    • no * as in the import statement,
    • no complex casting using the typeof keyword,
    • no extra dependencies like mocked.

提交回复
热议问题