如何使用 Jest 监视方法调用? [英] How can I use Jest to spy on a method call?
问题描述
我最近想测试在 React 组件的 componentDidMount
方法中是否有条件地调用了一些自定义方法.
I recently wanted to test that some custom method gets conditionally called in the componentDidMount
method of a React component.
componentDidMount() {
if (this.props.initOpen) {
this.methodName();
}
}
我使用 Jest 作为我的测试框架,其中包括用于模拟/间谍的 jest.fn()
.我已经读过,通过执行以下操作,使用 Sinon 进行测试非常简单:
I'm using Jest as my testing framework, which includes jest.fn()
for mocks/spies. I've read that this would be fairly trivial to test with Sinon, by doing something like the following:
sinon.spy(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
我正在尝试用 Jest 重新创建这个:
I'm trying to recreate this with Jest like so:
Component.prototype.methodName = jest.fn();
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
此代码失败并抛出以下错误:
This code fails and throws the following error:
jest.fn() value must be a mock function or spy.
Received:
function: [Function bound mockConstructor]
是否可以使用 Jest 测试此功能?如果是这样,如何?
Is it possible to test this functionality with Jest? And if so, how?
推荐答案
关键是在对象的 prototype
上使用 jests spyOn
方法.应该是这样的:
The key is using jests spyOn
method on the object's prototype
. It should be like this:
const spy = jest.spyOn(Component.prototype, 'methodName');
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();
如在此处找到的,例如:测试函数是否称为反应和酶
As found here e.g.: Test if function is called react and enzyme
请注意 最好在每次测试运行后清除间谍功能
let spy
afterEach(() => {
spy.mockClear()
})
https://facebook.github.io/jest/docs/en/jest-object.html#jestclearallmocks
这篇关于如何使用 Jest 监视方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!