【问题标题】:Unable to run JEST test无法运行 JEST 测试
【发布时间】:2021-10-28 20:27:48
【问题描述】:

当我尝试在 jest 测试文件中使用 require() 函数导入某些内容时遇到问题。

script2.test.js

const fetch = require('node-fetch');

it('test function', () => {
  expect(4).toEqual(4);
});

Package.json

{
  "name": "jest-test",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "scripts": {
    "test": "jest --watchAll"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.15.7",
    "@babel/core": "^7.15.8",
    "@babel/plugin-transform-async-to-generator": "^7.14.5",
    "@babel/preset-env": "^7.15.8",
    "jest": "^27.3.1"
  },
  "dependencies": {
    "node-fetch": "^3.0.0"
  },
  "jest": {
    "transform": {
      "^.+\\.(js|jsx)$": "babel-jest"
    }
  }
}

babel.config.cjs

module.exports = {presets: ['@babel/preset-env']}

当我使用 npm test 运行测试时出现以下错误

FAIL  ./script2.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax. 

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.


    Details:
    
        C:\work\jest-udemy\node_modules\node-fetch\src\index.js:9
        import http from 'http';
        ^^^^^^
    
        SyntaxError: Cannot use import statement outside a module
    
        > 1 | const fetch = require('node-fetch');
        |                   ^

我是 JEST 的新手,非常感谢任何帮助。 我的节点版本是 14.17.3 谢谢你。

【问题讨论】:

  • 你试过import fetch from 'node-fetch';而不是require吗?你的 package.json 中有 type: "module
  • @tromgy 是的,它仍然显示这个错误,SyntaxError: Cannot use import statement outside a module

标签: javascript node.js reactjs jestjs babel-jest


【解决方案1】:

似乎仍然需要跳过障碍才能使 ESM 发挥作用。

package.json 中将您的脚本更改为:

"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watchAll"

并且在 script2.test.js 中使用 import:

import fetch from 'node-fetch';

附:这是使用节点 14.15.1 测试的

【讨论】:

  • @tromy 这对我有用。!欣赏。谢谢。
猜你喜欢
  • 2022-01-05
  • 2019-10-21
  • 2021-10-15
  • 2020-11-25
  • 2022-08-07
  • 2015-07-31
  • 2023-04-02
  • 2020-09-22
  • 2020-05-07
相关资源
最近更新 更多