根据网络上的各种指南,配置Jest for Angular就像this一样简单:
ng new jest-test
cd jest-test
npm i -D jest jest-preset-angular
修改 package.json :
"test": "jest",
[...]
"jest": {
"preset": "jest-preset-angular",
"setupTestFrameworkScriptFile": "./src/setup-jest.ts"
},
setup-jest.ts :
import 'jest-preset-angular';
运行npm test
时,我仍然遇到此错误,
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:
jest-test/src/app/app.component.spec.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { TestBed, async } from '@angular/core/testing';
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
我尝试过在Web上找到的配置应用程序的无数种方法,都产生了此错误消息。
让我知道是否需要提供其他信息。
答案 0 :(得分:3)
如果您使用Angular CLI this库,将非常有帮助。
它将使您的工作区中清除与Jest设置相关的样板代码,并使用Angular CLI(ng test
)运行测试。
这也将节省您配置Jest的麻烦。
关于您的特定错误,它很可能与您的 tsconfig.spec.json 有关。您是否将module
字段更改为commonjs
?这是使Jest工作所必需的。
有关更多详细信息,请阅读this文章。
免责声明:我是该库的所有者。
答案 1 :(得分:0)
我在article之后尝试了几周。
一切顺利,但我决定不从茉莉花/业力转移到杰斯特。 原因:
答案 2 :(得分:0)
我使用Ionic,并希望通过Jest使Ionic 4和Angular 6正常运行。我找到了this blog post from Brian Love,并且紧随其后,并掌握了基础知识。附带说明一下,我在一个外部文件中配置了Jest,在这里显示了内容,因为我做了一些更改,但是现在在Angular 6下使用Jest运行了我的测试。
module.exports = {
collectCoverage: true,
collectCoverageFrom: [
"src/**/*.ts"
],
coverageDirectory: "<rootDir>/coverage/",
coveragePathIgnorePatterns: [
"node_modules",
"test-config",
"<rootDir>/src/app/interfaces",
"jestGlobalMocks.ts",
".module.ts",
"<rootDir>/src/app/main.ts"
],
},
preset: "jest-preset-angular",
roots: ['src'],
setupTestFrameworkScriptFile: "<rootDir>/src/setup-jest.ts",
transformIgnorePatterns: [
"node_modules/(?!(@ionic-native|@ionic|angularfire2)/)"
]
}