我正在尝试将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)
实际上,只要我需要一个模块,就会发生错误。有什么想法吗?
答案 0 :(得分:3)
即使安装了babel-jest,我仍然会收到此错误。
解决方案是在根目录中创建一个.babelrc
文件。在其中,您可以定义所需的预设,例如:
{
"presets": ["es2015", "react"]
}
此外,还有一个node_modules/jest-cli/.haste-cache
目录可能会导致过多的缓存。考虑使用preprocessCachingDisabled option禁用它。
答案 1 :(得分:2)
在将 Vendor.js 解析为 ES5 时出现此错误,它似乎没有在您的jasmine + jest测试中使用babeljs进行转换
有关在babeljs中使用jest的说明,请参阅https://babeljs.io/docs/using-babel/#jest