使用Jest监视componentDidMount中的方法调用 [英] Using Jest to spy on method call in componentDidMount
问题描述
我最近想测试一些自定义方法在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?
推荐答案
关键是使用jests spyOn
方法。它应该是这样的:
The key is using jests spyOn
method. It should be like this:
const spy = jest.spyOn(Component.prototype, 'methodName');
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();
如此处所示:测试函数是否被称为反应和酶
请注意,它是也是在每次测试运行后清除间谍功能的最佳做法
Please note, it is also best practice to clear the spied function after each test run
let spy
afterEach(() => {
spy.mockClear()
})
https://facebook.github.io/ jest / docs / en / jest-object.html#jestclearallmocks
这篇关于使用Jest监视componentDidMount中的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!