【问题标题】:ReferenceError: React is not defined in jest testsReferenceError:在开玩笑测试中没有定义 React
【发布时间】:2020-03-17 17:46:11
【问题描述】:

我有以下在浏览器中正确执行的行

eval(Babel.transform(template, { presets: ['react'] }).code);

但是当我运行玩笑测试时,我得到了ReferenceError: React is not defined

我错过了什么?

更多信息: 在测试文件中我有以下内容:

const wrapper = shallow(<MyComponent/>);
const instance = wrapper.instance();
instance.componentFunction(...)

然后componentFunction 有eval(Babel.transform(template, { presets: ['react'] }).code); 行,其中template 是它从测试文件中获取的东西,可以是&lt;span&gt;...&lt;/span&gt; 之类的东西

如果需要更多详细信息,请告诉我

【问题讨论】:

    标签: reactjs jestjs babel-jest


    【解决方案1】:

    如果您在 jest 测试文件中使用 JSX,则需要在文件顶部添加以下导入行:

    import React from 'react';
    

    原因是 Babel 将 JSX 语法转换为一系列 React.createElement() 调用,如果你导入 React 失败,这些调用都会失败。

    【讨论】:

    • 我在.test 文件中有import React from 'react';
    • 您还需要将它放在 component 文件中。例如,import React, { Component } from "react"; 至少,这解决了我的问题。
    【解决方案2】:

    Next.js 的最佳解决方案(jsx: 'preserve' 具体是: 按照下一个方式配置您的 babel 配置:(无需安装另一个 babel 插件):

    babel.config.js:

    module.exports = {
      presets: ['next/babel']
    };
    

    或者,如果遇到此错误的任何人遇到问题,其中 import React from 'react' 不是必需的,因为它已经包含在全局范围内并且不需要包含在每个文件中,那么此解决方案可能适合您。

    我只是简单地将 React 配置为以开玩笑的方式全局定义。

    我的jest.config.js:

    module.exports = {
      moduleDirectories: ['./node_modules', 'src'],
      // other important stuff
      setupFilesAfterEnv: ['<rootDir>/src/jest-setup.ts']
    }
    
    import '@testing-library/jest-dom';
    import React from 'react';
    
    global.React = React; // this also works for other globally available libraries
    

    现在我不需要担心每个文件都会导入 React(尽管 eslint 知道 Next.js 不需要这样做)

    【讨论】:

      【解决方案3】:

      @babel/preset 已经支持您的需求。根据react 17 documentation,我只需在babel.config.json 中将runtime 设置为automatic。

      {
        "presets": [
          ["@babel/preset-react", {
            "runtime": "automatic"
         }]
        ]
      }
      

      如果你使用@babel/plugin-transform-react-jsx,配置应该是

      {
        "plugins": [
          ["@babel/plugin-transform-react-jsx", {
            "runtime": "automatic"
          }]
        ]
      }
      

      通常不需要后者,因为@babel/preset-react 包含@babel/plugin-transform-react-jsx。


      为什么你不应该使用import React from 'react';

      documentation states:

      还有一个technical RFC 解释了新转换的工作原理。

      如果您想升级。 React 还提供了一个automated script,它可以从你的代码中删除不必要的导入。

      【讨论】:

        猜你喜欢
        • 2019-04-02
        • 1970-01-01
        • 2021-09-06
        • 1970-01-01
        • 1970-01-01
        • 2022-07-12
        • 2021-09-17
        • 2019-09-25
        • 2018-06-02
        相关资源
        最近更新 更多