我目前正在为我的 Angular2 组件中的一个模块编写一个测试模块,该模块使用 templateUrl 属性,因此需要在测试之前进行 TestBed.compileComponents 异步调用以进行编译。
我遇到的问题是 promise 回调 (then) 函数中的任何内容都根本不运行......就好像 promise 没有解决。
这是我的代码。
模块:
import { Component } from "@angular/core";
@Component({
selector: 'categories-component',
templateUrl: '/app/views/catalog/categories/categories-dashboard.html',
moduleId: module.id
})
export class CategoriesComponent {
title: 'Categories;
}
HTML 模板:
<h1>{{ title }}</h1>
和测试模块:
import {TestBed, ComponentFixture, ComponentFixtureAutoDetect, async} from "@angular/core/testing";
import { By} from "@angular/platform-browser";
import { CategoriesComponent } from "../../../../components/catalog/categories/CategoriesComponent";
import { DebugElement } from "@angular/core";
let comp: CategoriesComponent;
let fixture: ComponentFixture<CategoriesComponent>;
let de: DebugElement;
let el: HTMLElement;
describe('CategoriesComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ CategoriesComponent ],
providers: [
{ provide: ComponentFixtureAutoDetect, useValue: true }
]
});
});
it('should display original title', () => {
TestBed.compileComponents()
.then(() => {
fixture = TestBed.createComponent(CategoriesComponent);
comp = fixture.componentInstance; // BannerComponent test instance
// query for the title <h1> by CSS element selector
de = fixture.debugElement.query(By.css('h1'));
el = de.nativeElement;
expect(el.textContent).toContain(comp.title);
});
});
});
如您所见,在我的测试中,我调用 compileComponents 异步编译测试模块,然后在回调中创建测试组件的夹具和实例。这些都没有运行,我在其中添加了永远不会触发的断点。
谁能指出我在这里做错了什么?
谢谢!
最佳答案
因为测试是同步的
it('...', () => {
})
此处的回调执行,测试在回调函数执行后立即完成。
但问题是你的所有代码都在异步回调中
it('...', () => {
TestBed.compileComponents().then(() => {
// asynchronous
// code not executed
})
})
因此异步代码永远不会在测试完成之前执行。
这可以通过多种方式处理。您可以使用 native Jasmine done
回调
it('...', (done) => {
TestBed.compileComponents().then(() => {
/// do stuff
done();
})
})
这里,jasmine 给你传递了一个回调函数。完成所有异步操作后调用它是您的工作。
另一种方法是使用 Angular async
。
import { async } from '@anguar/core/testing';
it('...', async(() => {
TestBed.compileComponents().then(() => {
})
}))
这样做是将测试包装在一个测试区中,该测试区跟踪所有异步任务,并在所有异步任务完成后完成测试。在 jasmine 环境中,测试区实际上会在异步任务完成后调用 jasmine done
回调。
关于javascript - Angular2 测试。 Promise 从未在 TestBed.compileComponents 中解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41015892/