即使指定的方法正确执行,Jasmine spy也不会被调用

时间:2019-04-10 07:36:29

标签: angular testing jasmine spy

我目前在我的Angular项目中实施Jasmine。但是我不知何故偶然发现了一个带有间谍的奇怪行为。我已经在这里阅读了其他类似问题的问题,但是我不知道我应该如何解决我的具体情况。

我这样定义测试:

describe('DialogComponent', () => {
    let component: DialogComponent;
    let fixture: ComponentFixture<DialogComponent>;

    it('should open dialog and click', () => {
        const button = overlayContainerElement.querySelector('button');
        spyOn(component, 'doSmth').and.callThrough();
        // component.doSmth();          <-- this passes
        button.click();               // <-- this does not pass
        expect(component.doSmth).toHaveBeenCalled();
    });
});

我的HTML基本上只是一个带有执行方法的按钮的小表格,如下所示:

<button mat-flat-button (click)="doSmth()" class="mat-primary" type="button">Submit</button>

“ doSmth()”实现目前基本上只是相应打字稿文件中的占位符,将某些内容打印到控制台。

doSmth() {
    console.log('In doSmth()');
}

由于某种原因,我在运行测试时会收到“ In doSmth()”消息,但间谍表示未调用该方法。我尝试了其他一些方法,例如不是通过“ button.click()”执行该方法,而是通过“ component.doSmth()”执行该方法,该方法可以正常工作。有谁知道如何解决这个问题?

0 个答案:

没有答案