我有以下假设场景:
// file MyClass.js in an external package
class MyClass {
myfunc = () => {
// do something
}
}
// file in my project
function myFunctionToBeTested() {
const instance = new MyClass()
instance.myFunc()
}
我需要用 Jest 创建一个测试,确保 instance.myFunc
被调用
最佳答案
一种选择是用模拟实现替换 MyClass 模块
const mockmyfunc = jest.fn()
jest.mock("path/to/external/package/MyClass", () => {
return jest.fn().mockImplementation(() => {
return {myfunc: mockmyfunc}
})
})
然后编写如下测试
it("Test myfunc called in functionToBeTested", () => {
functionToBeTested()
expect(mockmyfunc).toHaveBeenCalled()
})
请注意,这不是唯一的方法,您可以深入研究 https://facebook.github.io/jest/docs/en/es6-class-mocks.html用于其他替代方案。
更新
如果 myfunc 是一个实际函数(我猜这不是一个选项,因为它是外部包?)
export class MyClass {
myFunc() {
// do smth
}
}
而且你不需要替换实现,你可以使用 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()
})
关于javascript - 如何使用 Jest 测试函数内部的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50380731/