簡體   English   中英

Mocking Jest 中的 React 上下文提供程序與 react-testing-library

[英]Mocking React context provider in Jest with react-testing-library

我有一個相當復雜的上下文,我環繞我的應用程序來處理身份驗證並提供從身份驗證服務檢索到的關聯數據。 我想繞過提供者的所有功能,只是模擬一個返回值。 當上下文呈現時,它會執行一堆我不想在測試時發生的初始化函數。

我在我的包裝器 function 中嘗試過這樣的事情:

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. 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。 沒有骰子。

無論如何,有人看到我在這里想要完成的事情嗎? 我只想模擬整個上下文,以便組件只獲得一個返回已知值的提供程序,而不執行任何上下文代碼。 react-testing-library 和 Jest 有可能嗎?

該錯誤意味着AuthContext.Provider不是 React 組件。 AuthContext是 Jest 間諜,即 function,它沒有Provider屬性。 由於AuthContext應該是 React 上下文,因此應該這樣定義。 對於默認導出,它應該是:

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

然后可以在測試中提供任何模擬值:

<AuthContext.Provider value={mockValue}>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM