使用 react-testing-library 在 Jest 中模拟 React 上下文提供者

Mocking React context provider in Jest with react-testing-library

我有一个相当复杂的上下文,我环绕我的应用程序来处理身份验证并提供从身份验证服务检索到的关联数据。我想绕过提供者的所有功能,只是模拟一个 return 值。当上下文呈现时,它会执行一堆我不想在测试时发生的初始化函数。

我在我的包装函数中尝试了类似的东西:

const mockValue = {
  error: null,
  isAuthenticated: true,
  currentUser: 'phony',
  login: jest.fn(),
  logout: jest.fn(),
  getAccessToken: jest.fn(),
}

const MockAuthContext = () => ( React.createContext(mockValue) )

jest.mock("../contexts/AuthContext", () => ({
  __esModule: true,
  namedExport: jest.fn(),
  default: jest.fn(),
}));

beforeAll(() => {
  AuthContext.mockImplementation(MockAuthContext);
});

const customRender = (ui, { ...renderOpts } = {}) => {
  const ProviderWrapper = ({ children }) => (
      <AuthContext.Provider>
         {children}
      </AuthContext.Provider>
  );
  return render(ui, { wrapper: ProviderWrapper, ...renderOpts });
};

// re-export everything
export * from "@testing-library/react";

// override render method
export { customRender as render };

唉,我得到一个错误: Error: Uncaught [Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

而且,事实上,如果我记录 Provider 呈现的内容,我得到:

    {
      '$$typeof': Symbol(react.element),
      type: undefined,
      ...

我试过将提供商设置为 AuthContext.getMockImplementation().Provider。没有骰子。

无论如何,有没有人看到我在这里想要完成的事情?我只想模拟整个上下文,这样组件就可以得到一个 return 已知值的提供者,而无需执行任何上下文代码。 react-testing-library 和 Jest 可以吗?

错误的意思是AuthContext.Provider不是React组件。 AuthContext 是 Jest 间谍,即函数,它没有 Provider 属性。由于 AuthContext 应该是 React 上下文,因此应该这样定义。对于默认导出,它应该是:

jest.mock("../contexts/AuthContext", () => ({
  __esModule: true,
  default: React.createContext()
}));

然后可以在测试中提供任何模拟值:

<AuthContext.Provider value={mockValue}>