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

标签 reactjs unit-testing jestjs react-hooks react-context

我正在尝试为我的 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/

相关文章:

javascript - 很好地格式化网格

ios - Xcode 11 单元测试 : Devices with iOS 12. * 未列出

reactjs - 在 Jest 中 stub I18next useTranslation 钩子(Hook)不会触发 toHaveBeenCalled

c# - 尝试使用 JustMock 对事件进行单元测试

javascript - 单元测试 Angular 属性指令

reactjs - Jest 没有实现 window.alert()

javascript - Vue + Jest 全局配置转移到规范文件中

javascript - 在 React 中使用本地 .json 文件时,import 和 fetch() 有什么区别

node.js - 如何解决对等依赖错误 : The package react@15. 3.2 不满足其 sibling 的 peerDependencies 要求

java - 使用 Fetch API 通过 React 应用程序调用 servlet - 出现“无法加载资源”错误(406 - Not Acceptable )