简体   繁体   English

Angular Karma JUnit 测试 - SpyOn 在私有方法中不起作用

[英]Angular Karma JUnit test - SpyOn does not work within private method

I try to test my component, I know the component works fine but my test gives error since Angular version has been updated to 12.我尝试测试我的组件,我知道该组件工作正常,但由于 Angular 版本已更新为 12,我的测试出现错误。

This is my component:这是我的组件:

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

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

And this is my test:这是我的测试:

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();
});

And still, this spyOn does not seem to work.而且,这个 spyOn 似乎不起作用。 I put a lot of console logs into my code and the doThis() method still get called but the log within my confirm method ('reject') does not get written to the console.我将大量控制台日志放入我的代码中,并且 doThis() 方法仍然被调用,但是我的确认方法('reject')中的日志没有写入控制台。 I cannot see why.我不明白为什么。

As I change the doThis() method to public and call it directy from my test as component.doThis(), then it runs to into the mocked myService.当我将 doThis() 方法更改为 public 并从我的测试中直接调用它作为 component.doThis() 时,它会运行到模拟的 myService 中。

Can anybody explain my why?有人可以解释我的原因吗?

Thanks a lot!非常感谢!

  1. You can call private methods in your spec either by casting to any您可以通过强制转换为任何来调用规范中的私有方法
(component as any).doThis();

or using []或使用 []

component['doThis']();
  1. You call fixture.autoDetectChanges() it may cause ngOnInit which is calling doThis before even you created the spy.你调用 fixture.autoDetectChanges() 它可能会导致 ngOnInit 它在你创建间谍之前调用 doThis 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM