【发布时间】:2019-09-04 08:50:28
【问题描述】:
我正在尝试为我的component App.js 设置测试,该测试将context 作为道具并返回提供者。问题是当我尝试测试它时,我传递给它的上下文总是解析为未定义。
我在组件中放置了一个控制台日志,并且在创建上下文和创建组件之间放置了一个控制台日志(它应该接收上下文作为参数)。由于某种原因,这导致组件中的 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 传递到我的组件中以创建提供程序,但它始终未定义。
【问题讨论】:
-
我相信你已经发现你的组件需要
contextprop但是Context被传递了。外壳很重要。
标签: reactjs unit-testing jestjs react-hooks react-context