如何使用 Jest 测试函数内的类实例

Yur*_*uri 5 javascript unit-testing reactjs jestjs

我有以下假设场景:

// file MyClass.js in an external package
class MyClass {
    myfunc = () => {
        // do something
    }
}

// file in my project
function myFunctionToBeTested() {
    const instance = new MyClass()
    instance.myFunc()
}
Run Code Online (Sandbox Code Playgroud)

我需要用 Jest 创建一个测试,确保instance.myFunc被调用

but*_*yyy 5

其中一种选择是用模拟实现替换 MyClass 模块

const mockmyfunc = jest.fn()
jest.mock("path/to/external/package/MyClass", () => {
  return jest.fn().mockImplementation(() => {
    return {myfunc: mockmyfunc}
  })
})
Run Code Online (Sandbox Code Playgroud)

然后编写以下测试

it("Test myfunc called in functionToBeTested", () => {
  functionToBeTested()
  expect(mockmyfunc).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)

请注意,这不是唯一的方法,您可以深入https://facebook.github.io/jest/docs/en/es6-class-mocks.html了解其他替代方法。

更新

如果 myfunc 是一个实际的函数(我猜这不是一个选项,因为它是外部包?)

export class MyClass {
    myFunc() {
      // do smth
    }
}
Run Code Online (Sandbox Code Playgroud)

并且您不需要替换实现,您可以使用 jest 的 automock

import MyClass from "path/to/external/package/MyClass"
jest.mock("path/to/external/package/MyClass")

it("Test myfunc called in functionToBeTested", () => {
  functionToBeTested()
  const mockMyFunc = MyClass.mock.instances[0].myFunc
  expect(mockMyFunc).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)