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 ?