【发布时间】:2018-03-19 15:44:47
【问题描述】:
我开始使用 Angular(v4.0.0) 开发一个小项目。在这个项目中,我正在添加单元测试。我阅读了angular testing documentation,现在对如何用 Angular 编写单元测试有了基本的了解。
在这方面,我正在努力为一个在 html 中触发 selectChange 事件的函数编写测试用例。
html的代码sn-p
html content
<div class="metabs">
<md-tab-group (selectChange)="selectMetabs($event)" [selectedIndex]="selectedIndex" *ngIf="!showAllMetabs">
<md-tab [label]="metab.name" *ngFor="let metab of dashboards"></md-tab>
</md-tab-group>
</div>
ts 的代码 sn-p
// Corresponding ts containing selectMetabs function
selectMetabs(event) {
console.log("--in select metabos--"); // this console is not getting printed
// rest of the code
}
现在我为此编写了测试用例:
describe('DashboardComponent', () => {
let fixture: ComponentFixture<DashboardComponent>;
let comp: DashboardComponent;
let de: DebugElement;
let el: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
DashboardComponent,
],
providers: [
],
imports: [
BrowserAnimationsModule,
AppMaterialModule,
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ],
}).compileComponents()
fixture = TestBed.createComponent(DashboardComponent)
comp = fixture.componentInstance
}))
it("should check selectMetabs function call", async(() => {
comp.showAllMetabs = false;
fixture.detectChanges();
let de = fixture.debugElement.query(By.css('.metabs > md-tab-group'));
let spy = spyOn(comp, 'selectMetabs');
de.triggerEventHandler('selectChange', {index: 0});
expect(spy).toHaveBeenCalled(); // pass test case
expect(spy).toHaveBeenCalledTimes(1); // pass test case
expect(comp.selectMetabolite).toHaveBeenCalledWith({index:0}); // pass test case
}))
我的这些测试用例都通过了,这向我保证 triggerEvent 正在工作。
我的困惑是,如果 selectMetabs 函数被调用,他们为什么没有打印控制台语句。
另外,这个函数也没有被测试覆盖。
我无法理解为什么会这样。我是角度测试的新手,这个问题让我很困惑。如果我遗漏了什么或需要提供更多信息,请告诉我。
我们将不胜感激有用的建议。谢谢!!
【问题讨论】:
标签: angular unit-testing jasmine angular-test