【发布时间】:2023-03-12 03:41:02
【问题描述】:
我有一个类,它在初始化时调用另一个方法,该方法调用另一个名为 pan 的方法。我正在尝试测试是否调用了 pan 方法。这个类比这更复杂,但我想要测试的只是 pan 被调用了。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.pan = this.pan.bind(this);
}
componentDidMount() {
initExternals();
}
initExternals() {
.. bla bla
this.pan();
}
pan() {
console.log('Function was called');
}
}
这是我的测试课
test('component should call initMap', () => {
const spy = jest.spyOn(WhereWeAreMap.prototype, 'pan');
const component = mount(<WhereWeAreMap />);
expect(spy).toHaveBeenCalled();
});
I have also tried.
test('component should call initMap', () => {
const component = mount(<WhereWeAreMap />);
const spy = jest.spyOn(component.instance(), 'pan');
wrapper.instance().forceUpdate();
expect(spy).toHaveBeenCalled();
});
我的测试出了什么问题,因为它无法测试组件方法 pan 被调用 expect(spy).toHaveBeenCalled()。日志显示它被调用,但我的测试显示不同。
预期的模拟函数已被调用,但未调用。
【问题讨论】:
-
你的
test函数应该做什么?你的组件在哪里渲染? -
它应该检查 pan 方法实际上是从 MyComponent 内部调用的。 MyComponent 被渲染为另一个组件的子组件。