簡體   English   中英

無法運行 JEST 測試

[英]Unable to run JEST test

當我嘗試在 jest 測試文件中使用 require() 函數導入某些內容時遇到問題。

腳本2.test.js

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

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

包.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 的新手,非常感謝任何幫助。 我的 Node 版本是 14.17.3 謝謝。

似乎仍然需要跳槽才能與 ESM 開玩笑。

package.json 中,將您的腳本更改為:

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

script2.test.js 中使用import

import fetch from 'node-fetch';

PS 這是用節點 14.15.1 測試的

暫無
暫無

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

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