解决core-js引起的Jest 23.x版本运行时SyntaxError

在使用3.3.0版本的可执行命令vue初始化一个项目时,通过一些选择,会得到一个带Jest的项目。 刚初始化完成时,Jest测试是可以通过的。 但是在一个测试文件中添加新的test时,就会发生错误。

错误

运行测试命令node node_modules/.bin/jest,得到以下错误:

  ● Test suite failed to run

    /private/tmp/javascript/tests/unit/TwoSum.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import "core-js/modules/es7.symbol.async-iterator";
                                                                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    SyntaxError: Unexpected string

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:402:17)

看上去是import "core-js/modules/es7.symbol.async-iterator"时,导致的问题。

而从能跑到不能跑,代码改动示例如下:

  describe('TwoSum.js', () => {
    test.each(TESTS)('nums=%s, target=%s, expect=%s', (nums, target, expected) => {
      expect(expected).toEqual(twoSum(nums, target));
    });
+
+   test('Invalid input', () => {
+     expect(() => twoSum([1, 2], 4)).toThrow(Error);
+   });
+ });

也就是说,只是在一个describe内加入了第二个test,竟然就会出错!

信息

以下为系统和NodeJS相关信息。

$ npx envinfo --preset jest
npx: 1 安装成功,用时 1.914 秒

  System:
    OS: macOS 10.14.5
    CPU: (4) x64 Intel(R) Core(TM) i7-4650U CPU @ 1.70GHz
  Binaries:
    Node: 12.4.0 - /usr/local/bin/node
    Yarn: 1.16.0 - /usr/local/bin/yarn
    npm: 6.9.0 - /usr/local/bin/npm

以下为Jest相关信息:

$ yarn why jest
yarn why v1.16.0
[1/4] 🤔  Why do we have the module "jest"...?
[2/4] 🚚  Initialising dependency graph...
[3/4] 🔍  Finding dependency...
[4/4] 🚡  Calculating file sizes...
=> Found "jest@23.6.0"
info Reasons this module exists
   - "@vue#cli-plugin-unit-jest" depends on it
   - Hoisted from "@vue#cli-plugin-unit-jest#jest"
info Disk size without dependencies: "40KB"
info Disk size with unique dependencies: "516KB"
info Disk size with transitive dependencies: "58.27MB"
info Number of shared dependencies: 181
✨  Done in 1.73s.

可见,问题版本是23.6.0

解决方案

虽然想直接给Jest提issue,但要填的信息太复杂。 折腾过程中,发现其最新版本似乎已经解决了。

package.json中,添加Jest最新版本24.8.0

  "resolutions": {
    "jest": "24.8.0"
  },

然后执行安装:

$ yarn install
yarn install v1.16.0
[1/4] 🔍  Resolving packages...
warning Resolution field "jest@24.8.0" is incompatible with requested version "jest@^23.6.0"
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...
✨  Done in 6.26s.

可以看到,确实有一条关于版本的warning。 但是,这个看上去由core-js导致的问题已经解决了。


相关笔记