![](/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.