我正在尝试测试反应组件的span标签的onClick。
<span id="A" onClick={this.changeImage}> Image A</span>
想要测试是否&#39; onClick&#39; &#39; changeImage&#39;函数是否被调用!
// 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.
有人可以指出我做错了什么吗?感谢。
答案 0 :(得分:1)
//修正了错误
describe('Tests', () => {
it('Should render without exploading', () => {
const wrapper = shallow(<Image />);
expect(wrapper).toHaveLength(1);
});
it('Should call changeImage() function on click', () => {
const spy = jest.spyOn(Image.prototype, 'changeImage');
const wrapper = shallow(<Image/>);
wrapper.find('#A').simulate('click', { target: { id: 'A' } });
expect(spy).toHaveBeenCalled();
spy.mockClear();//clearing the mock functions
});
});
在jest.spyOn()模拟函数之后放置包装器使测试工作。
在模拟函数的情况下,声明const的顺序很重要。需要首先声明间谍然后是包装器。在间谍之前声明包装将导致此错误:
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.