嗨,我有一个简单的组件需要测试:
MyComponent.js -----
import React from 'react';
const MyComponent = (props) => {
onClickHandler = () => {
console.log('clicked');
props.outsideClickHandler();
}
return (
<div>
<span className='some-button' onClick={onClickHandler}></span>
</div>
);
}
MyComponent.test.js ----
import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';
describe('MyComponent', () => {
const onClickHandler = jest.fn();
it('calls click event', () => {
const wrapper = shallow(<MyComponent />);
wrapper.find('.some-button').simulate('click');
expect(onClickHandler.mock.calls.length).toEqual(1); // tried this first
expect(onClickHandler).toBeCalled(); // tried this next
});
});
尝试了两种以上的期望值,我的控制台日志值即将到来
console.log('clicked'); comes
但是我的测试失败了,我得到了:
expect(received).toEqual(expected) // deep equality
Expected: 1
Received: 0
答案 0 :(得分:1)
因此,代码的问题是当您模拟click
事件时,您希望调用一个完全独立的模拟函数。您需要将模拟功能附加到组件。最好的方法是使用prototype
。像这样:
it('calls click event', () => {
MyComponent.prototype.onClickHandler = onClickHandler; // <-- add this line
const wrapper = shallow(<MyComponent />);
wrapper.find('.some-button').simulate('click');
expect(onClickHandler.mock.calls.length).toEqual(1);
expect(onClickHandler).toBeCalled();
expect(onClickHandler).toHaveBeenCalledTimes(1); // <-- try this as well
});
有关更多可能的解决方案,请参考this issue。