mercredi 23 septembre 2020

Mocking multiple react custom hooks with jest

I have a custom React hook that makes a async api call and returns the response. The implementation is as follows:

  const {
    response,
    call,
    loading,
  } = useAsyncRequest({
    args: [collection, uid, schema],
    callFn: apiGetDocument,
  });

I can then mock this component easily with jest like below:

AsyncRequestManager
      .mockReturnValue(defaultAsyncHookReturnLoad)

This works if I only use one of these hooks but if I used multiple (i.e. 1 for loading and 1 for saving) then I have to mock both responses separately as below:

AsyncRequestManager
      .mockReturnValueOnce(defaultAsyncHookReturnLoad)
      .mockReturnValueOnce(defaultAsyncHookReturnSave);

Which works for the same render but not for following rerenders.

Is it possible to tell jest to return in a value in sequence?

i.e something like the below (Which does not work because of scoped variables)

let i = 0;
AsyncRequestManager.mockImplementation(() => {
    if (i % 3 === 0) return defaultAsyncHookReturnLoad;
    if (i % 3 === 1) return defaultAsyncHookReturnSave;
    if (i % 3 === 2) return defaultAsyncHookReturnDelete
    i += 1;
});

Aucun commentaire:

Enregistrer un commentaire