【发布时间】:2018-05-25 11:53:41
【问题描述】:
我正在尝试测试反应组件的跨度标记的 onClick。
<span id="A" onClick={this.changeImage}> Image A</span>
想测试'onClick' 'changeImage' 函数是否被调用!
// test.js
describe('Tests', () => {
const wrapper = shallow(<Image />);
it('Should render without exploading', () => {
expect(wrapper).toHaveLength(1);
});
it('Should call changeImage() function on click', () => {
wrapper.instance().changeImage = jest.fn();
wrapper.update();
wrapper.find('#A').simulate('click', { target: { id: 'A' } });
expect(wrapper.instance().changeImage).toHaveBeenCalled();
});
});
也试过这个 -
it('Should call changeImage() function on click', () => {
const spy = jest.spyOn(wrapper.instance(), 'changeImage');
wrapper.find('#A').simulate('click', { target: { id: 'A' } });
expect(spy).toHaveBeenCalled();
});
两者都返回相同的错误。 // 错误
● Tests › Should call changeImage() function on click
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.
有人可以指出我做错了什么吗?谢谢。
【问题讨论】:
-
@OluwafemiSule 谢谢,从那个链接找出我做错了什么。 :)
-
您能否尝试存储对
wrapper.instance()的引用,而不是多次调用它来查看是否能解决问题?我想知道您是否每次都获得一个新实例
标签: javascript reactjs jestjs enzyme