2

I am mocking a function (react hook) to return something for a unit test, and would like to verify with a spy that it has been called only once.

This works fine for regular tests, but when trying to add test.concurrent.each, the spy appears to be shared across tests and the toHaveBeenCalledTimes is set to the number of tests run.

I tried to create a unique spy for each test, but it doesn't seem to matter:

export const mockLazyQuery = (result: TQueryResult): jest.SpyInstance => {
  const spy = jest.spyOn(Apollo, "useLazyQuery");

  spy.mockImplementationOnce(() => {
    return [jest.fn(), result];
  });
  return spy;
};

import { mockLazyQuery } from "../test-utils";

describe("useHasScope", () => {
  it.concurrent.each([
    [Role.STUDENT, fakeStudent],
    [Role.TRAINER, fakeTrainer],
  ])("should redirect a %s user to the home page", async (role, me) => {
    const querySpy = mockLazyQuery({
      data: { me },
      error: undefined,
      loading: false,
    });
    myIdVar(me.id);
    const wrapper: React.FC = ({ children }) => (
      <MemoryRouter>{children}</MemoryRouter>
    );
    renderHook(() => useHasScope(""), { wrapper });
    expect(querySpy).toHaveBeenCalledTimes(1);   // <== Failing because other tests calling useLazyQuery are running concurrently 
  });
});

Any idea how to keep the mock and spy state private within a test and allow to run several similar tests concurrently ?

Adrien Lemaire
  • 1,744
  • 2
  • 20
  • 29
  • 1
    Hello do you try this : "beforeEach(() => { jest.clearAllMocks(); });" could fix your problem maybe – La pach' Oct 28 '20 at 09:55
  • 1
    @Lapach' I have jest.clearAllMocks() setup on beforeEach, but it doesn't fix the problem. My issue is related to tests being run concurrently and sharing the same spy. – Adrien Lemaire Oct 30 '20 at 07:35

0 Answers0