单元测试:单击后应更改类

时间:2018-03-14 15:49:35

标签: angular unit-testing typescript karma-jasmine

当点击<mat-expansion-panel>Angular Material)时,它应该添加一个类mat-expanded但是每当我运行该函数时,当我记录它时DOM仍然是相同的,该类不会被添加

HTML

<mat-expansion-panel (opened)="toggleCollapseRow('open')" (closed)="toggleCollapseRow('closed')">
...

compononent.ts中的函数

public toggleCollapseRow(openOrClosed: string): void {
    if (openOrClosed === 'open') {
        this.expandCollapseIcon = 'ic_collapse_default';
    } else if (openOrClosed === 'closed') {
        this.expandCollapseIcon = 'ic_expand_default';
    }
}

单元测试

it('should expand on click', fakeAsync(() => {
    fixture.detectChanges();
    const panel = fixture.nativeElement.querySelector('mat-expansion-panel');
    const spy = spyOn(component, 'toggleCollapseRow').and.callThrough();
    panel.click();
    component.toggleCollapseRow('open');
    tick();
    fixture.detectChanges();
    // this logs the same output with no class added
    console.log(fixture.nativeElement.querySelector('mat-expansion-panel'));
    expect(spy);
    expect(component.toggleCollapseRow).toHaveBeenCalled();
    expect(component.expandCollapseIcon).toEqual('ic_collapse_default');
}));

这一切都成功但是当我添加以下内容时,它失败了,因为DOM仍然是相同的:

expect(fixture.nativeElement.querySelector('.mat-expanded')).toBeTruthy()

1 个答案:

答案 0 :(得分:1)

如果测试测试toggleCollapseRow如何工作,则不应该涉及点击。如果它测试模板的工作原理,则不应直接调用component.toggleCollapseRow('open')。由于这一点,期望是成功的。

正如the guide中所述,应使用DebugElement triggerEventHandler触发DOM事件,因为HTMLElement click不涉及绑定。

可能应该是:

const panelDE = fixture.debugElement.query(By.directive(MatExpansionPanel));
const spy = spyOn(component, 'toggleCollapseRow').and.callThrough();
panelDE.triggerEventHandler('click', null);
tick();
fixture.detectChanges();
expect(component.toggleCollapseRow).toHaveBeenCalled();
expect(component.expandCollapseIcon).toEqual('ic_collapse_default');
expect(panelDE.classes['mat-expanded']).toBeTruthy()