【发布时间】:2020-09-05 11:35:18
【问题描述】:
我正在处理一个我们最近在 Angular 9 中启动的项目,该项目是使用 Angular CLI 生成的。我想使用 Jest 而不是 Karma 来运行我的测试,因为在我看来,在你的构建管道中设置 Karma 的工作量太大(几年前我浪费了很多时间试图让 Karma 运行)。
我在尝试运行 Jest 时遇到错误:
ReferenceError: Zone is not defined
at node_modules/zone.js/dist/zone.js:670:5
at performance (node_modules/zone.js/dist/zone.js:8:9)
at Object.<anonymous> (node_modules/zone.js/dist/zone.js:9:2)
我安装 Jest 的步骤是:
- 自行安装 Jest
npm install -D jest jest-preset-angular @types/jest ts-jest
从 package.json 中移除所有 karma/jasmine 库
更新了 tsconfig.spec.json:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jest",
"node"
],
"esModuleInterop": true,
"emitDecoratorMetadata": true
},
"files": [
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
- 添加 jest.config.js:
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');
module.exports = {
preset: 'jest-preset-angular',
roots: ['<rootDir>/src/'],
testMatch: ['**/+(*.)+(spec).+(ts)'],
setupFilesAfterEnv: ['<rootDir>/src/setupJest.ts'],
collectCoverage: true,
coverageReporters: ['html'],
coverageDirectory: 'coverage/my-app',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {
prefix: '<rootDir>/'
})
};
删除 karma.conf.js
从 angular.json 中的架构师移除测试
从 ./src 中删除 test.ts
将“test”:“ng test”改为“test”:“jest”
在 ./src 中添加了 setupJest.ts:
import 'jest-preset-angular';
Object.defineProperty(window, 'CSS', {value: null});
Object.defineProperty(window, 'getComputedStyle', {
value: () => {
return {
display: 'none',
appearance: ['-webkit-appearance']
};
}
});
Object.defineProperty(document, 'doctype', {
value: '<!DOCTYPE html>'
});
Object.defineProperty(document.body.style, 'transform', {
value: () => {
return {
enumerable: true,
configurable: true
};
}
});
运行失败的测试示例如下:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MenuComponent } from './menu.component';
describe('MenuComponent', () => {
let component: MenuComponent;
let fixture: ComponentFixture<MenuComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MenuComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MenuComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
我不知道我做错了什么。我尝试了几个教程,还有一个使用@angular-builders/jest,但到目前为止都没有。我有一种感觉,使用 Ivy 渲染器的过渡可能会导致问题,但我不确定。我似乎在 Google 上找不到任何有同样问题的人,所以这把我带到了 StackOverflow。这里有人知道如何修复错误吗?
[编辑]
我在https://github.com/kayvanbree/jest-problem创建了我的问题的最小预生产
[编辑]
顺便说一句,这个问题的答案没有帮助:How to fix "zone is not defined" in this project
【问题讨论】: