rem*_*bir 5 javascript reactjs jestjs enzyme
我正在尝试测试反应组件的 span 标签的 onClick。
<span id="A" onClick={this.changeImage}> Image A</span>
Run Code Online (Sandbox Code Playgroud)
想测试 'onClick' 是否正在调用 'changeImage' 函数!
// 测试.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();
});
});
Run Code Online (Sandbox Code Playgroud)
也试过这个 -
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();
});
Run Code Online (Sandbox Code Playgroud)
两者都返回相同的错误。// 错误
? Tests › Should call changeImage() function on click
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.
Run Code Online (Sandbox Code Playgroud)
有人可以指出我做错了什么吗?谢谢。
//修正错误
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
});
});
Run Code Online (Sandbox Code Playgroud)
将包装器放在 jest.spyOn() 模拟函数之后使测试工作。
在模拟函数的情况下,声明 const 的顺序很重要。需要先声明 Spy,然后声明包装器。在间谍之前声明包装器将导致此错误:
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9357 次 |
| 最近记录: |