![](/img/trans.png)
[英]How to use ReactTestUtils to Simulate onChange event to update State
[英]How to simulate on `onChange` event that updates the state
我正在React中编写一个应用程序,并正在用Jest和Enzyme对其进行单元测试。
我有一个非常简单的组件,代表一个输入字段,其中包含以下代码:
// 'Container' component definition.
class Container extends React.Component<containerProps, containerState> {
static defaultProps = { };
state = {
hasValue: false
};
constructor(props: containerProps) {
super(props);
// Bind all the event handlers for the component.
(this: any).onChange = this.onChange.bind(this);
}
onChange(event: MouseEvent) : void {
this.setState(
{
hasValue: (event.target: window.HTMLInputElement).value !== ''
}
);
// Prevent a default browser event from happening.
event.preventDefault();
}
createComponentProps(): componentProps {
return {
cssClass: this.createComponentCssClass()
};
}
// Create the CSS class to pass to the component.
createComponentCssClass(): string {
let className = '';
if (this.state.hasValue) { className = className !== '' ? className + 'value' : 'value'; }
if (this.props.errorMessage && this.props.errorMessage !== '') {
className = className !== '' ? className + ' error' : 'error';
}
// Return the CSS class to apply to the component.
return className;
}
// Renders the 'Container' component.
render(): React$Element<any> {
return (
<Component {...this.createComponentProps()} />
);
}
}
因此,这是一个相当简单的组件。 现在,当输入字段的内容更改时,会发生状态更改,从而迫使将不同的CSS类应用于该组件。
我可以确认这是可行的,因为它已按预期在浏览器中运行。
现在,我正在编写一个单元测试,以验证使用以下代码将className value
传递给组件:
it('Passes down the \'cssClass\' property to the \'Input Field\' Component.', () => {
// Act.
const wrapper = mount(
<InputFieldContainer primaryThemeColor="TEAL" accentThemeColor="PINK" useAccentColor={true} />
);
wrapper.find('input').simulate('change', { target: { value: 'value' }});
wrapper.update();
// Assert.
expect(wrapper.find(InputFieldComponent).props().cssClass).toEqual('value');
});
因此,我正在渲染组件,模拟更改事件,并检查组件的CSS类属性,但是它是一个空字符串。 似乎状态更新没有更新(仅在单元测试中)。
使用console.log(wrapper.state())
在Jest中读取状态会给我一个JSON对象, console.log(wrapper.state())
具有hasValue: true
,所以状态会被更新,但是即使在调用wrapper.update()
,CSS类似乎也不会被通过。
我在这里想念什么?
亲切的问候
这似乎是酶的问题( https://github.com/airbnb/enzyme/issues/1153 )。
更新包装器后,您的组件应该同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.