使用 jest 和 react-testing-library 测试反应上下文

Rhi*_*omb 6 unit-testing reactjs jestjs react-context react-hooks

我正在尝试为我设置测试component App.js,将 acontext作为道具并返回一个提供者。问题是当我尝试测试它时,我传递给它的上下文总是解析为未定义。

我在组件中放置了一个控制台日志,并在创建上下文和创建组件(应该接收上下文作为参数)之间放置一个控制台日志。由于某种原因,这首先导致了组件中的 console.log。这可能就是为什么我得到上下文未定义的原因,因为它尚未初始化。

// Component/Provider
const App = (props) => {
  const {children, context} = props;
  const {data, dispatch} = useReducer(reducer);
  console.log(context); //undefined and this console.log runs first
  return <context.Provider value={useCallback(dispatch)}>{children}</context.Provider>
}
Run Code Online (Sandbox Code Playgroud)

在我的 test.js 中

import React, {useContext} from 'react';
import {render} from 'react-testing-library';
import {App} from './App';
const context = React.createContext();

function Provider(children) {
  console.log(context); //Is correct but runs second
  return <App Context={context}>{children}</App>;
}

const customRender = (ui, options) =>
  render(ui, { wrapper: Provider, ...options });

const Consumer = () => {
  const dispatch = useContext(context);
  returns <Button onClick={dispatch({type: 'Do something'})}>Whatever</Button/>;
}
customRender(<Consumer />)
Run Code Online (Sandbox Code Playgroud)

我应该能够将 a 传递Context到我的组件中以创建提供程序,但它始终未定义。

Ben*_*ams 0

也许这是一个拼写错误,但是您的文件真的被称为吗test.js?如果是这样,您需要将其更改为.jsx,因为您在测试中使用 JSX(例如在Provider组件中)。