首页 > 解决方案 > 如何在并发测试中获得独特的玩笑间谍?

问题描述

我正在模拟一个函数(反应钩子)以返回一些用于单元测试的东西,并且想用一个间谍来验证它只被调用过一次。

这适用于常规测试,但在尝试添加时test.concurrent.each,间谍似乎在测试之间共享,并且 toHaveBeenCalledTimes 设置为运行的测试数。

我试图为每个测试创建一个唯一的间谍,但这似乎并不重要:

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 
  });
});

知道如何在测试中保持模拟和间谍状态私有并允许同时运行几个类似的测试吗?

标签: typescriptjestjsmockingreact-hooksspy

解决方案


推荐阅读