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

Cru*_*ink 10 mocking reactjs jestjs react-context react-testing-library

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

我在我的包装函数中尝试了类似的方法:

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 };
Run Code Online (Sandbox Code Playgroud)

唉,我收到一个错误: 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.

事实上,如果我记录该提供程序呈现的内容,我会得到:

    {
      '$$typeof': Symbol(react.element),
      type: undefined,
      ...
Run Code Online (Sandbox Code Playgroud)

我尝试将提供程序设置为 AuthContext.getMockImplementation().Provider。没有骰子。

无论如何,有人看到我在这里想要完成什么吗?我只想模拟整个上下文,以便组件只获得一个返回已知值的提供程序,而不执行任何上下文代码。React-testing-library 和 Jest 可以做到这一点吗?

Est*_*ask 7

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

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

然后可以在测试中提供任何模拟值,如下所示:

<AuthContext.Provider value={mockValue}>
Run Code Online (Sandbox Code Playgroud)