簡體   English   中英

Jest - ReferenceError:沒有為簡單的測試文件定義定義

[英]Jest - ReferenceError: define is not defined for a simple test file

我正在嘗試使用 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錯誤

那是因為我們有@babel/plugin-transform-modules-amd以便在處理測試任務時,代碼將轉換為define() AMD 格式,這就是錯誤define來源。 為 jest 測試指定 babel 配置可以解決這個問題。

// 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 參考 / 使您的 Babel 配置具有玩笑意識


關於轉換后的代碼,此命令將顯示測試代碼的緩存目錄,

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

打開該文件夾,您可能會在jest_dx/jest-transform-cache-{HASH}/{QueueNumber}看到一些文件,該文件就在那里。

問題出在我的.babelrc 改為:

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

錯誤消失了:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM