首页 > 解决方案 > 在另一个测试中设置 Jest 模拟的指针

问题描述

我正在编写一个测试工厂,并希望公开一个“setupMocks”式函数指针来模拟一些常见的 API 响应。但是,它不起作用。这是我所拥有的:

测试-utils.ts

export const setupMocks = () => {
  jest.mock(...);
  jest.mock(...);
  ...
  jest.mock(...);
}

组件.test.tsx

// Test passes if these are uncommented, and are identical to the lines in setupMocks
// jest.mock(...);
// jest.mock(...);
// ...
// jest.mock(...);

describe("test component", () => {
  const props = { ... };
  beforeEach(() => {
    setupMocks();
  });
  
  afterEach(() => {
    jest.resetAllMocks(); // already tried commenting out this line; it's not this
  });

  it("something", () => {
    const component = render(<Component {...props} />);
    expect(component.someStateDependentOnMockedDataFromJestCall).toBe(true); // fails
  });
});

标签: reactjsunit-testingjestjs

解决方案


推荐阅读