首页 > 解决方案 > Jest - Jest 遇到了意外的令牌。香草JS

问题描述

我正在尝试用 JavaScript 制作一个复杂的 zip 提取器,我认为单元测试非常重要。话虽如此,一位朋友推荐了 Jest。我无法让我的任何测试工作,所以我做了一个愚蠢的测试,确保我的 JS Enum 的第一个值为 0。然而,Jest 每次都失败说它遇到了一个意外的令牌

我尝试了一个更复杂的测试并将其简化为这个简单的测试:

枚举.js:

const Format = {
    UNKNOWN: 0,
    ZIP: 1,
    TAR_GZIP: 2,
    TAR_BZIP: 3,
};

export default Format

枚举.test.js

const {Format} = require("../src/enums.js");

test("bad test", () => {
   expect(Format.UNKNOWN).toBe(0);
});

给我的错误是这样的:

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/giovanni/WebstormProjects/extract.js/src/enums.js:7
    export default Format;
    ^^^^^^

    SyntaxError: Unexpected token export

    > 1 | const Format = require("../src/enums.js");
        | ^
      2 | 
      3 | test("bad test", () => {
      4 |    expect(Format.UNKNOWN).toBe(0);

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
      at Object.<anonymous> (test/enum.test.js:1:1)

标签: javascriptjestjs

解决方案


使用 Bable 解决了这个问题。一旦我用 NPM 安装了 Babel,我添加了一个包含内容的文件 .babelrc:

{
  "presets": ["@babel/preset-env"]
}

这行得通。


推荐阅读