0

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.

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. 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. 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.

Can anybody explain my why?

Thanks a lot!

dorcsi
  • 295
  • 2
  • 6
  • 24

1 Answers1

0
  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 call ngOnInit which is calling doThis before even you created the spy.
gourav arora
  • 131
  • 6