【问题标题】:Jest - ReferenceError: define is not defined for a simple test file开玩笑 - ReferenceError:没有为简单的测试文件定义定义
【发布时间】:2019-04-02 23:40:52
【问题描述】:

我正在尝试使用 jest 来测试我的项目,但是在运行 npm run test 时,即使我的测试文件非常简单,我也会得到 ReferenceError: define is not defined

test("Adding 1 + 1 equals 2", () => {
  expect(1 + 1).toBe(2);
});

这导致我认为我的设置配置错误,但我认为我的配置中没有做任何可能导致这种情况的事情(我认为)。

当我在测试用例中没有直接使用define 时,为什么它告诉我define 没有定义,我很困惑。我将不胜感激任何指针!

谢谢!

编辑:这是我的package.json

"jest": {
  "collectCoverageFrom": [
    "src/**/*.{js,jsx,mjs}"
  ],
  "testMatch": [
    "**/__tests__/**/*.js?(x)",
    "**/?(*.)+(spec|test).js?(x)"
  ],
  "testEnvironment": "node",
  "testURL": "http://localhost",
  "transform": {
    "^.+\\.(js|jsx|mjs)$": "./node_modules/babel-jest",
    "^.+\\.css$": "./config/jest/cssTransform.js",
    "^(?!.*\\.(js|jsx|mjs|css|json)$)": "./config/jest/fileTransform.js"
  },
  "transformIgnorePatterns": [
    "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
  ],
  "moduleNameMapper": {
    "^react-native$": "react-native-web"
  },
  "moduleFileExtensions": [
    "web.js",
    "js",
    "json",
    "web.jsx",
    "jsx",
    "node",
    "mjs"
  ]
}

编辑 2:我发现即使我的测试文件中没有任何内容,我也会得到相同的 ReferenceError: define is not defined 错误

【问题讨论】:

标签: javascript reactjs jestjs


【解决方案1】:

那是因为我们有@babel/plugin-transform-modules-amd,因此在处理测试任务时,代码将转换为define() AMD 格式,这就是错误define 的来源。指定 jest test 的 babel config 可以解决这个问题。

// babel.config.js
module.exports = api => {
  const commonConfig = {/* preset configs or something */};
  if( !api.env("test") ){
    commonConfigs.plugins.push("@babel/plugin-transform-modules-amd");
  }

  return commonConfig;
}

Jest API Reference / Making your Babel config jest-aware


关于转换后的代码 该命令将显示测试代码的缓存目录,

npx jest --showConfig | grep cacheDirectory
# /private/var/folders/dc/7gkfb6ns0c79ll9gv2y3m6_w0010gn/T/jest_dx

打开那个文件夹你可能会在jest_dx/jest-transform-cache-{HASH}/{QueueNumber}看到一些文件,文件就在那里。

【讨论】:

    【解决方案2】:

    问题出在我的 .babelrc 中。改为:

    {
      "env": {
        "test": {
          "plugins": []
        },
        "development": {
          "plugins": [
            "transform-es2015-modules-amd"
          ]
        }
      },
      "presets": [
        "react",
        "es2015",
        "stage-2"
      ],
      "sourceMaps": false,
      "ignore": [
        "build",
        "node_modules"
      ]
    }
    

    错误消失了:-)

    【讨论】:

    • 您好@Tim,您的 .babelrc 中解决问题的具体更改是什么?
    • @DarrylR.Norbert 如果我没记错的话是我的环境有问题
    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 2021-09-17
    • 2017-11-01
    • 2021-09-06
    • 2021-07-17
    相关资源
    最近更新 更多