使用 Jasmine 在 Angular 8 中测试异步代码时如何等待?



我已经设法使用Karma和Jasmine在Angular 8应用程序中设置了自动单元(组件(测试。它正确地运行了所有测试,并以体面的方式显示组件内容(可以看到数据如何实际更改组件(。

但是,我希望能够不时减慢测试运行速度,以查看组件在每次测试后的外观。当然,这不是管道所必需的,但对于某些调试会话 + 演示目的来说会很好。

我尝试使用afterEach函数来执行长tick,但函数结束的速度比预期的要快得多。

const testBedConfiguration = {
imports: [
ComponentTestingModule,
CustomCoreModule
],
declarations: [TableLevelTagListComponent],
providers: [
// mocked services
{ provide: LoggingService, useClass: MockedLoggingService },
{ provide: SecurityTagCustomService, useClass: MockedSecurityTagCustomService },
{ provide: SecurityTagsService, useClass: MockedSecurityTagsService}
]
};
describe("TableLevelTagListComponent", () => {
let component: TableLevelTagListComponent;
let fixture: ComponentFixture<TableLevelTagListComponent>;
const getDebugElement = () => fixture.debugElement;
const btnLoadFromApi = () => getDebugElement().query(e => e.nativeElement.id === "btnLoadFromApi").nativeElement;
beforeEach(async(() => {
TestBed.configureTestingModule(testBedConfiguration)
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TableLevelTagListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
afterEach(fakeAsync(() => {
console.log("Trying to wait after the test");
tick(1000);
}));
it("TableLevelTagListComponent should be created", () => {
expect(component).toBeTruthy();
});
it("positive testing of getting information from own API",
fakeAsync(inject( [SecurityTagCustomService], (tagService: MockedSecurityTagCustomService) => {
setupSimpleMockService(tagService, fixture, () => {
console.log("Btn load from api", btnLoadFromApi());
btnLoadFromApi().click();
});
component.tagList$.subscribe(tags => {
console.log("Received some tags from own API: ", tags);
fixture.detectChanges();
expect(tags.length).toBeGreaterThan(3);
expect(tags[0].id).toEqual("TableTag1");
});
})));

我正在使用 ngrx/Store,我所有的测试都是异步的(fakeAsync(。

问:使用 Jasmine 在 Angular 8 中测试异步代码时如何等待?

正如我在评论中提到的,解决您的问题的一个快速且相对直接的解决方案是简单地使用async()setTimeout()来实现使用 Jasmine 在 Angular 8 中的实际等待时间。

您在afterEach()中展示了它,或者它也可以替换it()规范中的逻辑,但是直接修改答案中的子句看起来就像您显示的那样,为了清楚起见,仅在此处复制,因为上面的注释不允许适当的间距:

afterEach(async(() => {
console.log("Trying to wait after the test");
setTimeout(() => { }, 1000);
}));

最新更新