我正在尝试为我的 component App.js
设置测试接收 context
作为 Prop 并返回提供者。问题是当我尝试测试它时,我传递给它的上下文总是解析为未定义。
我在组件中放置了一个控制台日志,并在创建上下文和创建组件(应该接收上下文作为参数)之间放置一个控制台日志。由于某种原因,这首先导致了组件中的 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>
}
在我的 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 />)
我应该可以通过
Context
进入我的组件以创建提供程序,但它始终未定义。
最佳答案
也许这是一个错字,但你的文件真的叫 test.js
?
如果是这样,您需要将其更改为 .jsx
,因为您在测试中使用 JSX(例如在 Provider
组件中)。
关于reactjs - 使用 jest 和 react-testing-library 测试 react 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671102/