4

I have a Wizard contains steps, each step has its own validation (sync/async).

for example:

<Wizard>
   <Form1 />
   <Form2 />
   <Form3 />
</ Wizard>

Each form contains onContinue method which validates the form inputs.

onContinue = async () => {
    let step = this.steps[this.state.step];
    let validation = await step.validate();
    // check for error and change step number.
    this.changeStep(this.state.step + 1, validation);
};

Now I'm trying to test the behavior of the Wizard, by making sure, when clicking onContinue, the step number Increased by 1.

it('should set the state property "step" to 1 after successfully clicking the continue button', () => {
      const props = {
        id: 'testId',
        children: noErrorChildren
      };
      const wizard= mount(<Wizard {...props} />);
      tree.find('onContinue-button').simulate('click');
      expect(wizard.state().step).toEqual(1);
});

After running the test, this error shows up:

Error: expect(received).toEqual(expected)

Expected value to equal:
  1
Received:
  0
Expected :1
Actual   :0

the step variable is not increased to 1 as expected.

Thanks.

Şivā SankĂr
  • 1,966
  • 1
  • 18
  • 34
H.Hinn
  • 73
  • 2
  • 7
  • what is `onContinue` ? is it a `onClick={onContinue}` ? – AlexZvl Mar 31 '19 at 09:07
  • Possible duplicate of [Testing with React's Jest and Enzyme when simulated clicks call a function that calls a promise](https://stackoverflow.com/questions/37408834/testing-with-reacts-jest-and-enzyme-when-simulated-clicks-call-a-function-that) – jonrsharpe Mar 31 '19 at 09:08
  • did you check this? https://stackoverflow.com/a/51045733/3305456 – AlexZvl Mar 31 '19 at 09:09
  • @AlexandrZavalii Yes didn't work – H.Hinn Mar 31 '19 at 09:10

1 Answers1

5

The reason why the step variable is not increased as expected is because onContinue is an async function, and your test file did not attempt to wait for a response. Since it is async, and you treated it as a normal function the code continued to execute without waiting for the result.

Try doing this and see if it helps,

In your it block you can specify the anonymous function as async, like so:

it('should do some stuff...', async () => {

and then before the tree.find method, add the await keyword

await tree.find('onContinue-button').simulate('click');
Trevor Johnson
  • 874
  • 5
  • 19
  • 1
    I'm trying to consistently get this to work but the await seems to only work by accident and not by design. There is still a [race condition](https://github.com/enzymejs/enzyme/issues/823#issuecomment-433089259) because simulate doesn't return a promise to actually wait for. – HMR Apr 22 '20 at 23:09