0

我尝试测试我的组件,我知道该组件工作正常,但我的测试给出了错误,因为 Angular 版本已更新到 12。

这是我的组件:

ngOnInit() {
    if (versonA) {
        this.doThis();
    } else {
        this.doThat();
    }
}

private doThis() {
this.myService.confirm({
        message: message,
        accept: () => {
            this.doAcceptLogic();
        }, reject: () => {
            console.log('reject')
            this.doRejectLogic();
        }
    });
}

这是我的测试:

beforeEach(async () => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.autoDetectChanges();
    spyOn(TestBed.get(MyService), 'confirm').and.callFake((params: Confirmation) => {
        params.reject();
    });
    await fixture.whenStable();
});

而且,这个 spyOn 似乎不起作用。我将很多控制台日志放入我的代码中,doThis() 方法仍然被调用,但我的确认方法('reject')中的日志没有被写入控制台。我不明白为什么。

当我将 doThis() 方法更改为 public 并直接从我的测试中将其调用为 component.doThis() 时,它会运行到模拟的 myService 中。

谁能解释我的原因?

非常感谢!

4

1 回答 1

0
  1. 您可以通过强制转换为任何来调用规范中的私有方法
(component as any).doThis();

或使用 []

component['doThis']();
  1. 您调用 fixture.autoDetectChanges() 它可能会调用 ngOnInit,它甚至在您创建间谍之前调用 doThis。
于 2021-11-05T09:52:04.680 回答