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

问题描述 投票:0回答:1

我在一个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中接收的另一个函数。父组件函数定义为...

reactjs unit-testing enzyme
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.