0

我正在尝试使用 Jest 来测试我的节点 API。我有一个简单的 npm 脚本,它调用 jest

{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "jest",
    "precommit": "lint-staged"
  },
  "dependencies": {
    "@koa/cors": "^2.2.1",
    "apollo-link-http": "^1.5.4",
    "apollo-server-koa": "^1.3.6",
    "axios": "^0.18.0",
    "dotenv": "^6.0.0",
    "graphql": "^0.13.2",
    "graphql-tools": "^3.0.4",
    "koa": "^2.5.1",
    "koa-bodyparser": "^4.2.1",
    "koa-router": "^7.4.0",
    "node-fetch": "^2.1.2"
  },
  "devDependencies": {
    "husky": "^0.14.3",
    "jest": "^23.3.0",
    "lint-staged": "^7.2.0",
    "nodemon": "^1.17.5",
    "prettier": "^1.13.7"
  },
  "lint-staged": {
    "gitDir": "./",
    "*.{js,json}": [
      "prettier --no-semi --print-width 140 --tab-width 2 --write",
      "git add"
    ]
  },
  "jest": {
    "bail": true,
    "verbose": true,
    "testMatch": [
      "<rootDir>/**/*.test.js"
    ]
  }
}

我的 jest 配置中有一个 jest 配置,package.json它告诉 jest 要测试什么:

"jest": {
    "bail": true,
    "verbose": true,
    "testMatch": [
      "<rootDir>/**/*.test.js"
    ]
  }

我在我的项目中根本没有使用 babel,但是由于某种原因,当我尝试在其中运行我的一个测试时./test.test.js

test("Example test", () => {
  expect(true).toBe(true)
})

我收到以下错误:

$ jest
 FAIL  ./test.test.js
  ● Test suite failed to run

    Couldn't find preset "env" relative to directory "/Users/<myusername>/Projects"

      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19
          at Array.map (<anonymous>)
      at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
      at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
      at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
      at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
      at new File (node_modules/babel-core/lib/transformation/file/index.js:135:24)
      at Pipeline.transform (node_modules/babel-core/lib/transformation/pipeline.js:46:16)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        7.563s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

我尝试添加一个 babel env 预设,但仍然遇到相同的错误。我认为我也不应该仅仅为了测试而添加一个 babel 配置。

我正在运行节点版本8.11.3和纱线1.7.0,并使用版本在项目本地安装了 jest^23.2.0

我如何告诉 jest 不要担心 babel env?

4

2 回答 2

6

babel-jest安装 Jest 时会自动添加。如果您不打算转译 ES6 代码(看起来像您的情况),也许只需重置配置:

// package.json
{
  "jest": {
    "transform": {}
  }
}
于 2018-07-06T13:53:22.970 回答
0

当您忘记添加 babel-preset-env 依赖项时,通常会发生此错误。

正如您已经说过您尝试了此解决方案,请尝试查看它是否是 babel-preset-env 的某个特定版本。

您使用的是哪个版本?

于 2018-07-06T13:45:42.900 回答