首页 > 解决方案 > 使用 ES6 导入语句节点运行测试

问题描述

我在 ubuntu 上使用 nodev15.0.1和 jest 。26.6.018.04.5

我已经设置了一个简单的测试用例,并在文件顶部尝试使用 ES6 导入语句:

import Color from './color.js'

test("Initialized properly after construction", () => {
    expect(1 + 1).toBe(2);
});

此外,这里是 color.js 的代码:

class Color {
    constructor(r, g, b, a) {
        this.r = r;
        this.g = g;
        this.b = b;
        this.a = a;
    }
}

export {
    Color
};

当我运行 jest 时,我得到以下错误输出:


 FAIL  src/modules/color.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /home/daniel/Documents/raycaster/src/modules/color.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Color from './color.js'
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at new Script (node:vm:100:7)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.288 s
Ran all test suites.
npm ERR! code 1

基于 Jest 文档https://jestjs.io/docs/en/ecmascript-modules,我已将以下内容添加到我的package.json文件中:

"type": "module",
"jest": {
        "testEnvironment": "jest-environment-node",
        "transform": {}
}

尽管有这些配置,但 jest 似乎无法在 ES6 兼容模式下运行。我需要做哪些配置才能启用导入语句?

标签: javascriptnode.jsjestjses6-modules

解决方案


我找到了Node v13 / Jest / ES6 — 对没有 babel 或 esm 的模块的原生支持

其中突出显示了我需要的部分:

在我的package.json文件中,我需要指定以下内容:

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

推荐阅读