1

I am new to the React and Jest and I am trying to test my function where : I have a function :

handleSubmit = (e) => {
    this.changeData().then(() => {
        const payload = {
            somePayload: 'sample'
        };
        this.props.actions.authenticate(payload);
    });
};

and the jest function as :

it('test mock test', () => {
    const actionsMock = { authenticate: jest.fn() };
    const localWrapper = shallow(<SomeComponent actions={actionsMock} />);
    const instance = localWrapper.instance();
    jest.spyOn(instance, 'handleSubmit');
    instance.forceUpdate();
    localWrapper.find('.button').simulate('click');
    expect(actionsMock.authenticate).toHaveBeenCalledWith({somePayload: 'sample'});
});

So, In this case, when I click on the button it calls the handlesubmit function and eventually the this.props.actions.authenticate(payload); but when I assert the same in Jest it gives me error that function was never called.

EDIT

As in the comment CJ Pointed: I see that my assertion is getting called even before the promise for changeData resolved. So, How I can I make my assertion wait till the promise gets resolved?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
vaibhav
  • 762
  • 2
  • 12
  • 34
  • Hi @vaibhav! I have not yet attempted to recreate this, but from inspection it appears the issue might be that since changeData() is returning a promise, your assertion might be called before the promise is resolved. Try putting a console.log(1) after the simulated button click, right before the assertion, and a console.log(2) right before the authenticate call to see which executes first. If they are called in the correct order, then we can look at what else could be causing the issue. – CJNaude Jun 13 '19 at 12:59
  • Oh you were absolutely right, @CJNaude. This indeed was the issue. my assertion is getting called before the promise could return the value. Any Solution to that? Also, I am updating my question for the same. – vaibhav Jun 13 '19 at 13:20
  • 1
    Hi @vaibhav this seems to be a feasible solution for your problem: https://stackoverflow.com/a/51045733/3977134 – r3dst0rm Jun 13 '19 at 13:28
  • Here's the official jest docs on dealing with promises in tests: https://jestjs.io/docs/en/asynchronous.html#promises You can also mock the changeData function so that it executes synchronously, but I suppose at that point your test is just checking that handleSubmit is called and authenticate is in there. – CJNaude Jun 13 '19 at 13:38
  • 1
    @r3dst0rm. this is exactly I was looking for. Thanks for the help. – vaibhav Jun 13 '19 at 14:03
  • 1
    @CJNaude, Thaks a lot for pointing the mistake and then navigating to the right direction for the solution :) – vaibhav Jun 13 '19 at 14:03

0 Answers0