我的角度测试有问题。我不知道这是一个错误还是我做错了什么。
我有2个组成部分。一种在ngOnInit中使用promises,另一种则完全为空。
使用promise的组件如下所示:
import {Component, OnInit} from '@angular/core';
import {User, UserManager} from 'oidc-client';
@Component({
selector: 'app-test',
templateUrl: './test-promise.component.html',
styleUrls: ['./test-promise.component.css']
})
export class TestPromiseComponent implements OnInit {
private readonly userManager: UserManager;
public async ngOnInit(): Promise<any> {
return this.getDataStore('', '', '');
}
public getDataStore(url: string, key: string, keyType: string): Promise<any> {
return this.getToken();
}
public getToken(): Promise<string> {
return this.getUser().then(user => {
return user.access_token;
});
}
public getUser(): Promise<User> {
return this.userManager.getUser();
}
}
在import语句中,您可以看到我具有哪些依赖关系以及使用Oidc Client的依赖关系。
我的其他组件看起来像这样(只是空的):
import { Component } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent {
}
创建新组件时,这两个组件的测试规范都遵循标准规范,因此对于使用promise的组件,如下所示:
describe('TestPromiseComponent', () => {
let component: TestPromiseComponent;
let fixture: ComponentFixture<TestPromiseComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
TestPromiseComponent
]
}).compileComponents().then();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestPromiseComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should create', () => {
expect(component).toBeTruthy();
});
});
那是我的设置。现在非常奇怪的是,当我运行测试时,TestComponent会失败-即使实际上是TestPromiseComponent失败了。在这里查看结果:
因此,现在提出一个大问题:即使实际上是TestPromiseComponent失败,为什么TestComponent也会失败?
谁能向我解释一下:)
编辑1:
这是TestComponent的测试:
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
TestComponent
]
}).compileComponents().then();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should create', () => {
expect(component).toBeTruthy();
});
});
编辑2:
我正在运行以下版本的业力和茉莉花:
“茉莉花芯”:“〜2.99.1”,
“ jasmine-spec-reporter”:“〜4.2.1”,
“ karma”:“〜1.7.1”,
“ karma-chrome-launcher”:“〜2.2.0”,
“业报-伊斯坦布尔报道”:“〜2.0.0”,
“业力茉莉花”:“〜1.1.1”,
“ karma-jasmine-html-reporter”:“ ^ 0.2.2”,
最佳答案
奇怪的是有2个beforeEach(还有一个async),我不知道jasmine怎么调用相同的(并行?是它们的定义顺序吗?顺便说一句,您错过了async函数中的await关键字,因此您没有正确返回a答应会导致测试的奇怪行为:)
beforeEach应该更像:
beforeEach(() => {
return TestBed.configureTestingModule({
declarations: [
TestComponent
]
}).compileComponents().then( () => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
}));
关于angular - Angular 6-生命周期 Hook 中的 promise 使其他测试失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52475475/