【发布时间】:2019-02-18 06:59:17
【问题描述】:
出于某种原因,我的fakeAsync 测试无法解决简单的承诺。我创建了一个显示问题的最小示例(主要是ng-生成的样板文件)。
我的测试组件在其ngOnInit 方法中包含一个简单的直接承诺解析:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-simple-test',
templateUrl: './simple-test.component.html',
styleUrls: ['./simple-test.component.scss']
})
export class SimpleTestComponent implements OnInit {
constructor() { }
message: string;
ngOnInit() {
Promise.resolve('hello').then((content: string) => this.message = content);
}
}
我正在使用以下测试来测试这个承诺:
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { SimpleTestComponent } from './simple-test.component';
describe('SimpleTestComponent', () => {
let component: SimpleTestComponent;
let fixture: ComponentFixture<SimpleTestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SimpleTestComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should display "hello"', fakeAsync(() => {
tick();
expect(component.message).toBe('hello');
}));
});
但是测试失败了,这意味着在expect 的时候这个promise 没有得到解决,尽管通过tick() 强制解决了promise。
在测试开始时向component.ngOnInit() 添加另一个显式调用时,它可以工作。但这会导致ngOnInit() 被调用两次。据我所知,beforeEach() 中的fixture.detectChanges() 无论如何都应该照顾ngOnInit()。
我错过了什么?为什么在tick() 期间没有解决承诺?
【问题讨论】:
标签: angular typescript testing jasmine