【问题标题】:Jest - Test an ES6 classJest - 测试一个 ES6 类
【发布时间】:2021-12-06 14:21:41
【问题描述】:

我正在学习使用 Jest 测试我的 JavaScript。我有一个基本项目是这样设置的:

/
  /src
    myClass.js
  /tests
    myClass.test.js
  package.json

代码如下所示:

myClass.js

export class MyClass {
  constructor() {
    this.result = null;
  }

  calculate() {
    this.result = 1;
    return this.result;
  }
}

myClass.test.js

import { MyClass } from '../src/myClass';

test('Calculate', () => {
  let myObject = new MyClass();
  let result = myObject.calculate();
  expect(result).toBe(1);
});

package.json

{
    "name": "sample-project",
    "version": "0.0.1",
    "type":"module",
    "scripts": {
        "dev": "vite",
        "build": "vite build",
        "serve": "vite preview",
        "test": "jest"
    },
    "dependencies": {
        "vue": "^3.2.16",
        "vue-router": "^4.0.11"
    },
    "devDependencies": {
        "@vitejs/plugin-vue": "^1.9.3",
        "jest": "^27.3.1",
        "vite": "^2.6.4",
        "vite-plugin-html": "^2.1.1",
        "vite-plugin-singlefile": "^0.5.1"
    }
}

当我使用 npm run test 运行测试时,它只执行 jest,我收到一条错误消息:SyntaxError: Cannot use import statement outside a module

我做错了什么?如何从 Jest 测试 MyClass

【问题讨论】:

标签: javascript jestjs


【解决方案1】:

请关注Jest's Getting Started Guide 中的Babel 部分

简单运行:

yarn add --dev babel-jest @babel/core @babel/preset-env

并在项目根目录下创建babel.config.js文件,内容如下:

// babel.config.js
module.exports = {
  presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};

仅供参考: Jest 在后台使用虚拟节点环境。如果我没记错的话,支持的最旧的 Node 版本是 10。因此,如果您想使用 ES6 功能,则需要配置像 Babel 这样的源代码转换器。 (Source)

【讨论】:

  • 我将babel.config.js 添加到我的项目的根目录(即/)。当我运行 npm run test 时,我收到一条错误消息:babel.config.js: Error while loading config - You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.
  • 我认为这可能是您的Node版本引起的!?请看:stackoverflow.com/questions/61146112/…
  • 也许将其重命名为babel.config.cjs 可行!?
  • 成功了!谢谢!
猜你喜欢
  • 2018-09-14
  • 1970-01-01
  • 2017-10-17
  • 2019-02-28
  • 2017-01-12
  • 2017-02-25
  • 2015-07-10
  • 2015-07-19
  • 1970-01-01
相关资源
最近更新 更多