【发布时间】:2017-08-31 21:15:12
【问题描述】:
我最近想测试一些自定义方法是否在 React 组件的 componentDidMount 方法中被有条件地调用。
componentDidMount() {
if (this.props.initOpen) {
this.methodName();
}
}
我使用 Jest 作为我的测试框架,其中包括用于模拟/间谍的 jest.fn()。我已经读到,通过执行以下操作,使用 Sinon 进行测试是相当简单的:
sinon.spy(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
我正在尝试像这样用 Jest 重新创建它:
Component.prototype.methodName = jest.fn();
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
此代码失败并抛出以下错误:
jest.fn() value must be a mock function or spy.
Received:
function: [Function bound mockConstructor]
是否可以使用 Jest 测试此功能?如果有,怎么做?
【问题讨论】:
标签: javascript reactjs testing jestjs enzyme