我在一个React应用程序的单元测试用例中有一种情况,其中一个函数需要从父组件的props中接收的另一个函数。父组件函数定义如下:
onSavePropClick(action) {
const save = this.saveProperty(action);
if(action === SAVE){
return () => new Promise(() => {
resolve(this.calculate().then(save));
});
}
return save;
}
此函数调用已作为道具传递给子组件,其形式为>]
<MyComponent finalSave={this.onSavePropClick(SAVE)} />
MyComponent具有功能:
savingAndShowResults() { const { finalSave, onClose } = this.props; finalSave().then(() => { onClose(); }); return true; }
现在,当我对执行的执行进行测试时,由于“无法读取未定义的属性,然后抛出该错误,测试如下”
const initialProps={ finalSave: jest.fn(), onClose: jest.fn() }; it(‘should handle saving and show results’, () => { const component = shallow( <MyComponent {...initialProps} /> ); component.instance().savingAndShowResults(); expect(initialProps.finalSave).toHaveBeenCalled(); expect(initialProps.onClose).toHaveBeenCalled(); });
我无法弄清楚为什么即使解决了Parent组件功能的承诺也给了我这个错误。请提出建议。
我在一个React应用程序的单元测试用例中有一种情况,其中一个函数需要从父组件的props中接收的另一个函数。父组件函数定义为...
假设initialProps.finalSave
是一个模拟函数,您需要确保要从initialProps.finalSave
返回一个承诺: