使用 Jest 时出现意外的保留字错误

Unexpected reserved word error using Jest

我正在尝试将 Jest 测试添加到我的项目中(使用 React、Browserify 和 Babel),但是我在做最基本的事情时遇到错误:

采用这种结构:

|- /app
  |- /scripts    
    |- /models
      |- Vendor.js
      |- /__tests__
         |- Vendor-test.js

还有这段代码:

Vendor.js:

class Vendor {
  constructor(json) {
   this.id = json.vendor_id;
  }
}

module.exports = Vendor;

供应商测试:

jest.dontMock('../Vendor.js');

describe('Vendor', function() {
 it('Vendor creation', function() {
     var Vendor = require('../Vendor');
     var vendor = new Vendor({vendor_id:1});
     expect(vendor.id).toBe(1);
   });
 });

这是我遇到的错误:

app/scripts/models/Vendor.js: Unexpected reserved word
        at Contextify.sandbox.run (/Users/jasalguero/work/projects/monoqi/b2b-frontend/node_modules/jest-cli/node_modules/jsdom/node_modules/contextify/lib/contextify.js:12:24)
        at JSDomEnvironment.runSourceText (/Users/jasalguero/work/projects/monoqi/b2b-frontend/node_modules/jest-cli/src/JSDomEnvironment.js:108:22)
        at Object.runContentWithLocalBindings (/Users/jasalguero/work/projects/monoqi/b2b-frontend/node_modules/jest-cli/src/lib/utils.js:345:23)
        at Loader._execModule (/Users/jasalguero/work/projects/monoqi/b2b-frontend/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:250:9)
        at Loader.requireModule (/Users/jasalguero/work/projects/monoqi/b2b-frontend/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:916:12)
        at Loader.requireModuleOrMock (/Users/jasalguero/work/projects/monoqi/b2b-frontend/node_modules/jest-cli/src/HasteModuleLoader/HasteModuleLoader.js:937:17)
        at Spec.<anonymous> (/Users/jasalguero/work/projects/monoqi/b2b-frontend/app/scripts/models/__tests__/Vendor-test.js:5:18)
        at jasmine.Block.execute (/Users/jasalguero/work/projects/monoqi/b2b-frontend/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:1065:17)
        at jasmine.Queue.next_ (/Users/jasalguero/work/projects/monoqi/b2b-frontend/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2098:31)
        at null._onTimeout (/Users/jasalguero/work/projects/monoqi/b2b-frontend/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2088:18)
        at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

实际上,当我需要一个模块时,错误就发生了。有什么想法吗?

Vendor.js 解析为 ES5 时出现此错误,似乎它没有在您的 babeljs 中进行转译茉莉+笑话测试

有关将 jest 与 babeljs 结合使用的说明,请参阅 https://babeljs.io/docs/using-babel/#jest

即使在安装了 babel-jest 之后,我也一直收到这个错误。

解决方案是在根目录中创建一个 .babelrc 文件。在其中定义所需的预设,例如:

{
    "presets": ["es2015", "react"]
}

此外,还有一个 node_modules/jest-cli/.haste-cache 目录可能会导致过多的缓存。考虑使用 preprocessCachingDisabled option.

禁用它