Leff
Leff

Reputation: 1350

Jest testing promise in React gives TypeError: Cannot read property 'finally' of undefined

I have a child component MySummary that calls the function passed from the parent component like this:

submit() {
    this.setState({submitting: true});
    this.props.handleSubmit()
      .finally(() => {
        if (!this.mounted) {
          return;
        }
        this.setState({submitting: false, showConfirmDialog: false});
      });
  }

And in the parent component the handleSubmit function returns a promise and redirects on submit to another page:

handleSubmit() {
    return this.gateway.submitExam()
      .then((exam) => {
        this.setState(exam);
        this.props.history.push('/exam/result');
      });
  }

In browser it seems to be working. And even though I thought finally would never been called because we redirect to another page, and the child component would be unmounted then, it seems that it still reaches that block of code. I have logged into console from the finally block when I was running that code. So I am not sure how is that happening. The problem I have is that my test is failing and that I get the error:

TypeError: Cannot read property 'finally' of undefined

In my test I am clicking on a button that calls the submit function, and then I am just checking if the handleSubmit function was called:

I am mounting the component like this:

< MySummary exam={exam} handleSubmit ={jest.fn()}/>

And this is the test implementation:

const submitButton = confirmDialog.findByProps({'data-testid': 'submit-exam'});
submitButton.props.onClick();
expect(mySummary.props.handleSubmit).toHaveBeenCalled();

But, that test gives the error mentions above. I assume the error comes from wrong implementation of the prop handleSubmit, which is only defined as jest.fn(). How can I mock the promise implementation so that I can get this test to work?

Upvotes: 1

Views: 3670

Answers (1)

Remolten
Remolten

Reputation: 2682

You need your mocked function to return a Promise, like the actual function does. So, try setting the mock's return value to a resolved Promise:

handleSubmit={jest.fn(() => Promise.resolve())}

See An Async Example and Mock Functions from the Jest docs for more info.

Upvotes: 5

Related Questions