test xstate final state

241 views Asked by At

I'm trying to test the login of my state machine written with Xstate. I'm wondering how I can test the login and the state-change, let me do an example: my state machine is doing these 3 steps: init (with guard) -> step 1 (service call) -> errorState (because I mocked the service call with a reject).

I wrote this test:

  const fetchService = interpret(mockedMachine).onTransition((state) => {
    console.log(state.value);
  });

  fetchService.start();

  expect(
    fetchService.getSnapshot().matches('errorState')
  ).toBeTruthy();

console log show that all my states are correct but unfortunately the getSnapshot it's not giving the last state from my machine. I can't use "onDone" because this is not my final state and my machine it's very big for a complex schema. How I can test it?

1

There are 1 answers

0
chautelly On

Await the expected outcome

await waitFor(
  () =>  expect(
    fetchService.getSnapshot().matches('errorState')
  ).toBeTruthy();
)