通过触发selectChange事件角度测试来调用函数



我开始在Angular(v4.0.0)中做一个小项目。在这个项目中,我添加了单元测试。我阅读了angular测试文档,现在对如何用angular编写单元测试有了基本的理解。

在这篇文章中,我正在为一个从html触发selectChange事件的函数编写测试用例。

html的代码片段

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的代码片段

// 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函数被调用,那么为什么控制台语句没有被打印出来。

此外,此功能也未包含在测试范围内。

我不明白为什么会发生这种事。我是角度测试的新手,这个问题让我很困惑。如果我遗漏了什么,或者我需要提供更多信息,请告诉我。

有用的建议将不胜感激。谢谢

之所以会发生这种情况,是因为您正在用let spy = spyOn(comp, 'selectMetabs');模拟组件的selectMetabs方法。这也是你正在测试的。

就单元/集成测试而言,这是非常错误的。这是因为,在单元/集成测试中,不应该模拟被测试的东西的方法(这里是您的组件)。您应该只模拟组件所依赖的其他东西的方法(例如服务的方法)。

一旦你删除了这个间谍let spy = spyOn(comp, 'selectMetabs');,它应该调用你组件的方法,它应该被覆盖。

现在出现的问题是:在这种情况下,你应该期待什么

好吧,您在组件的selectMetabs方法中执行console.log("--in select metabos--");。因此,您可以模拟console.log,然后期望它被调用。

希望能有所帮助。

最新更新