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
到我的组件中以创建提供程序,但它始终未定义。