开玩笑:无法读取未定义的属性

时间:2020-03-14 10:19:21

标签: reactjs unit-testing enzyme

我的反应测试应用程序的单元测试用例中存在一种情况,其中一个函数需要从父组件的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)} onClose={()=>this.setState({closeWindow: true})} />

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组件功能的承诺后,也会给我这个错误。 请提出建议。

1 个答案:

答案 0 :(得分:2)

假设initialProps.finalSave是一个模拟函数,则需要确保您从initialProps.finalSave返回了诺言:

const initialProps = {
  finalSave: jest.fn().mockImplementation(() => Promise.resolve());
  ...
};