【发布时间】:2020-09-14 17:01:49
【问题描述】:
您好,我有一个简单的组件需要测试:
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
});
});
尝试了上面两种expect,我的控制台日志值来了
console.log('clicked'); comes
但我的测试失败了,我得到了这个:
expect(received).toEqual(expected) // deep equality
Expected: 1
Received: 0
【问题讨论】:
-
你能做一个codesandbox吗?
-
您的
onClickHandler与<MyComponent />没有任何关联,因此不会被调用。
标签: reactjs testing jestjs enzyme