【问题标题】:how to fix React-Redux Provider and connect not available in jest如何修复 React-Redux Provider 并在玩笑中连接不可用
【发布时间】:2021-03-11 22:21:31
【问题描述】:

我想用 redux&hocks 测试一个当前工作的 react 组件

使用默认的 react-cli 测试框架开玩笑我做了这个测试文件

import React from "react";
import { render as rtlRender, fireEvent, screen } from "@testing-library/react";
import { createStore } from "redux";
import RRdx, { Provider } from "react-redux";
import MyComponent from "./";

/* some code */

console.log("the source of my paint", RRdx, Provider);

function render(ui, storeData) {
  const store = getStore(storeData);
  const Wrapper = function ({ children }) {
    return <Provider store={store}>{children}</Provider>; // this pops an error
  };
  return rtlRender(ui, { wrapper: Wrapper });
}

/* the rest of the test */

控制台打印输出:

 console.log src/components/MyComponent/MyComponent.test.js:55
    the source of my paint { useDispatch: [Function: useDispatch] } undefined

  console.error node_modules/react/cjs/react.development.js:315
    Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
    
    Check your code at MyComponent.test.js:53.
        in Wrapper

所以,¿我在测试设置中缺少什么来查看提供程序? (也可以连接,但我找到了一个很好的解决方法)

我正在遵循 react 和 redux 官方测试指南(不含 enzime)。

【问题讨论】:

  • 提供最少的、可重现的测试代码和组件代码。

标签: reactjs redux react-redux jestjs react-testing-library


【解决方案1】:

您可以将此添加到您的 jest 配置中,它会模拟 useSelectoruseDispatch 挂钩,但会保持 react-redux 的其余部分不变,包括 Provider

jest.mock('react-redux', () => {
  return {
    ...jest.requireActual('react-redux'),
    useSelector: jest.fn().mockImplementation(() => ({})),
    useDispatch: () => jest.fn(),
  };
});

【讨论】:

    【解决方案2】:

    最后,其他一些测试脚本正在模拟来自 react-redux 的这些属性,所以从副作用行为中我得到了这些错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 2018-09-01
      • 2017-08-25
      • 2019-08-12
      • 1970-01-01
      • 2017-12-08
      相关资源
      最近更新 更多