6
votes

I have situation in my unit test case for a react application, where in a function calls for another function received in props from parent component. The parent component functions definition is something like this:

onSavePropClick(action) { 
    const save = this.saveProperty(action);
    if(action === SAVE){
        return () => new Promise(() => {
            resolve(this.calculate().then(save));
       });
    }
return save;
}

This function call has been passed as props to the child component as

<MyComponent finalSave={this.onSavePropClick(SAVE)} onClose={()=>this.setState({closeWindow: true})} />

MyComponent has a function:

savingAndShowResults() {
const { finalSave, onClose } = this.props;
finalSave().then(() => {
onClose();
});
return true;
}

Now when I have a test for the executed, it throws me error as “Cannot read property then of undefined”, the test is as follows

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();
});

I am not able to figure out why even on resolving in return in promise of Parent component’s function, gives me this error. Please suggest.

1
Please update your code to include initialProps, it's difficult to know what's wrong without it. - helloitsjoe
Done please check - OM The Eternity

1 Answers

12
votes

Assuming initialProps.finalSave is a mock function, you need to make sure you're returning a promise from initialProps.finalSave:

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