Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!