为角度配置Jest

nuk*_*uke 5 typescript jestjs angular

根据网络配置玩笑的角度对各种指南是那么容易,因为这个

ng new jest-test
cd jest-test
npm i -D jest jest-preset-angular
Run Code Online (Sandbox Code Playgroud)

修改package.json

"test": "jest",
[...]
"jest": {
    "preset": "jest-preset-angular",
    "setupTestFrameworkScriptFile": "./src/setup-jest.ts"
},
Run Code Online (Sandbox Code Playgroud)

setup-jest.ts

import 'jest-preset-angular';
Run Code Online (Sandbox Code Playgroud)

但是,在运行时,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)
Run Code Online (Sandbox Code Playgroud)

我尝试了在Web上找到的配置应用程序的无数变化,所有这些都会产生此错误消息。

让我知道是否需要提供其他信息。

Mas*_*sta 1

几周前我按照这篇文章进行了尝试。

一切都很顺利,但我决定不再从 Jasmine/Karma 转到 Jest。原因:

  • 我需要在多个真实浏览器上运行 UT,而 Jest 无法做到这一点。(阅读Jest 存储库上的讨论
  • 我还可以使用 Jasmin 使用 Protractor 或 Selenium-Webdriver 编写 e2e 测试