Javascript React不会在jest测试中调用复选框的onchange回调
我正在编写一些使用复选框函数的代码(我已经剥离了很多功能)Javascript React不会在jest测试中调用复选框的onchange回调,javascript,reactjs,unit-testing,jestjs,Javascript,Reactjs,Unit Testing,Jestjs,我正在编写一些使用复选框函数的代码(我已经剥离了很多功能) 导出类MyLovelyCheckBox扩展React.Component{ 建造师(道具){ 超级(道具); 如果(this.props.isRequired)this.props.updateType('default'); } 手动检查(复选框){ 如果(复选框。选中){ this.props.updateType(checkbox.value); }否则{ this.props.updateType(“”); } } render
导出类MyLovelyCheckBox扩展React.Component{
建造师(道具){
超级(道具);
如果(this.props.isRequired)this.props.updateType('default');
}
手动检查(复选框){
如果(复选框。选中){
this.props.updateType(checkbox.value);
}否则{
this.props.updateType(“”);
}
}
render(){
返回
;
}
}
复选框
功能是(再次剥离):
其中,实用方法create
为:
const create = (params, required = {}, shallowlyRender = true) => {
const props = {
type: 'generic',
updateType: () => true,
};
const allProps = { ...props, ...params };
return shallowlyRender
? shallow(<MyLovelyCheckBox {...allProps} />)
: mount(
<Provider store={store}>
<MyLovelyCheckBox {...allProps}/>
</Provider>,
);
};
我在这个测试中哪里出错了?在您的测试中,您似乎正在为变更事件处理程序传递一个“updateType”道具,但是您的组件希望使用一个“handleChecked”道具,对吗?我看不到您在测试设置中指定手动检查道具的位置。但也许我这里遗漏了什么。@Florian updateType是从handle checked调用的,handle checked是通过的。哦,我遗漏了一些:)@Florian你有什么想法吗?不幸的是,没有,我更习惯于反应测试库的方式。我可以详细说明我将如何使用RTL实现这一点,但这并不能回答您的问题……也许您可以尝试测试回调触发的视觉效果(像真实用户一样测试)作为解决方法?这是RTL philisophy顺便说一句:)。
it('when clicked, updateTypes is called', () => {
const updateType = jest.fn().mockReturnValue(true);
const mountedComponent = create({ updateType }, false, false);
const checkBox = mountedComponent.find('Checkbox');
checkBox.simulate('change', { target: { checked: true } });
expect(updateType).toHaveBeenLastCalledWith(true);
});
const create = (params, required = {}, shallowlyRender = true) => {
const props = {
type: 'generic',
updateType: () => true,
};
const allProps = { ...props, ...params };
return shallowlyRender
? shallow(<MyLovelyCheckBox {...allProps} />)
: mount(
<Provider store={store}>
<MyLovelyCheckBox {...allProps}/>
</Provider>,
);
};
expect(jest.fn()).toHaveBeenLastCalledWith(...expected)
Expected: true
Received: ""
Number of calls: 0