[英]How to test a function that updates state in a component with jest
Here is a snippet of my application 这是我的应用程序的片段
constructor(props) {
super(props);
this.state = {
searchText:""
};
}
handleSelectionInput = (e) => {
this.setState({searchText:e.target.value});
}
How do i test the handleSelectionInput. 我如何测试handleSelectionInput。
You can do that using enzyme. 您可以使用酶做到这一点。 check below example where i did test onchange event
检查以下示例,我在其中测试了onchange事件
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { shallow, configure } from 'enzyme';
import Input from './Input';
configure({ adapter: new Adapter() });
test('Date with default date value handle click', () => {
const component = shallow(
<Input
name="input"
id="input"
error
pattern=".*"
transformValue={value => value}
/>
);
expect(component.state().value).toEqual('');
component.find('#input').simulate('change', { target: { name: 'input', value: '02' } });
expect(component.state().value).toEqual('02');
component.find('#input').simulate('blur', { target: { name: 'input', value: '02' } });
expect(component.state().value).toEqual('02');
});
Hope this helps you. 希望这对您有所帮助。
I found the solution to my problem, the issue was not to simulate but rather work with the instance of the wrapper as seen below 我找到了解决问题的方法,问题不是模拟,而是使用包装器实例,如下所示
it("Test handleSelectionInput", () => {
expect(wrapper.state('searchText')).toBe("");
instance.handleSelectionInput({ target: { name: 'input', value: '02' } });
expect(wrapper.state('searchText')).toBe("02");
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.