По некоторым причинам, мои 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
, несмотря на принудительное разрешение обещания через tick()
.
Работает при добавлении еще одного явного вызова к component.ngOnInit()
в начале теста. Но это приводит к тому, что ngOnInit()
вызывается дважды. Насколько я знаю, fixture.detectChanges()
в beforeEach()
должен позаботиться о ngOnInit()
в любом случае.
Что мне не хватает? Почему обещание не выполняется в течение tick()
?