'How do I assert a function was called after a successful response from a RTKQ Mutation hook?

I am calling a mutation hook once a form submits, then when that update is successful (has data), call a function passed in via props. I am not sure if the correct usage of an RTKQ mutation hook is per the following code:

const MyFormComponent = (props) => {
  const [updateThing, { data }] = usePutThingMutation();

  // Do something after data updated successfully
  useEffect(() => {
    if (data) props.onSubmit(data);
  }, [data]);

  const handleSubmit = async (changes) => {
    await updateThing(changes);
  };

  return <form onSubmit={handleSubmit}></form>;
};

The code does work as expected, however I am hitting an issue when writing tests that I cannot assert props.onSubmit() was ever called. Using @testing-library/react my test looks like:

const onSubmit = jest.fn();
// render component
render(<MyFormComponent onSubmit={onSubmit} />);
// populate form
// click 'submit' button
// expect `onSubmit()` to be called once
userEvent.click(submitButton);
await waitFor(() => expect(props.onSubmit).toHaveBeenCalledTimes(1));

Output is:

Expected number of calls: 1

Received number of calls: 0

I have tried to .unwrap() by moving the call to props.onSubmit() within the handleSubmit method with updateThing(changes).unwrap().then(data => props.onSubmit(data)) which still works but the test fails.

Given that props.onSubmit() is expected to have been called once after a successful action, what is the correct approach to asserting the call to props.onSubmit() has been called?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source