Opo*_*sum 3 testing jasmine typescript angular
由于某种原因,我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在通过以下测试来测试这个承诺:
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');
}));
});
Run Code Online (Sandbox Code Playgroud)
expect但测试失败,这意味着尽管通过 强制承诺解决,但承诺在 时尚未得到解决tick()。
component.ngOnInit()当在测试开始时添加另一个显式调用时,它会起作用。但这会导致ngOnInit()被调用两次。据我所知,无论如何fixture.detectChanges()都beforeEach()应该照顾ngOnInit()好。
我缺少什么?为什么承诺在 期间没有得到解决tick()?
发现问题了。在区域之外的函数中ng g component生成测试,因此无法通过 解析 Promise 。fixture.detectChanges()beforeEach(...)fakeAsynctick()
搬进fixture.detectChanges()这个fakeAsync区域对我来说解决了这个问题:
beforeEach(() => {
fixture = TestBed.createComponent(SimpleTestComponent);
component = fixture.componentInstance;
});
it('should display "hello"', fakeAsync(() => {
fixture.detectChanges();
tick();
expect(component.message).toBe('hello');
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2087 次 |
| 最近记录: |