【问题标题】:Mocked Apollo Provider with React testing library is not returning data带有 React 测试库的模拟 Apollo Provider 不返回数据
【发布时间】:2022-11-28 01:00:29
【问题描述】:

几天来我一直在尝试解决这个问题,但我仍然不知所措。

我有一个使用 Apollo Client 的 React 应用程序,我想使用 React 测试库测试一个组件。省略所有不相关的细节,我的主文件代码如下所示:

const ComponentToTest = () => {
  ...
  const { data, loading } = useComponentRespQuery({
    variables: {
      id: idValue
    },
    skip: !idValue
  });

  if (loading) {
    return <>Loading</>;
  }
  ...
}

测试是这样写的:

export const componentRespMock = {
  request: {
    query: componentRespDocument
  },
  result: {
    data: {
      response: {
        ...
      }
    }
  }
};

const componentRender = (mockGraphQLData: any, initialEntry: string = "") => render(
  <MemoryRouter initialEntries={[initialEntry]}>
    <MockedProvider mocks={[ mockGraphQLData ]} addTypename={false}>
        <ComponentToTest />
    </MockedProvider>
  </MemoryRouter>
);

describe("ComponenToTest", () => {
  it("should render a component to test", async() => {
    componentRender(zoneMock);
    const placeHolderValues = await screen.findByText(/Bla/i);
    expect(placeHolderValues).toBeInTheDocument();
  });
  ...
}

我可以自信地说,这种测试方式以前在我的代码库中是有效的。我在测试的时候找到了一个让Apollo返回正确值的方法,就是把useComponentRespQuery里面的代码全部注释掉。 以前有人遇到过它并且知道如何解决它吗?

【问题讨论】:

    标签: reactjs react-hooks apollo-client react-apollo


    【解决方案1】:

    在不知道 MockedProvider 提供商的幕后情况的情况下很难说。但是,根据我使用 mock 的经验,它们应该始终匹配 (1:1),尤其是当您在 useComponentRespQuery 中注释掉 { variables: { id: idValue }, skip: !idValue } 时它有效。
    我建议仔细检查 zoneMock 以确保它符合您的期望

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-23
      • 1970-01-01
      • 2016-11-18
      • 2021-11-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2018-07-20
      相关资源
      最近更新 更多