0

Jasmine can be used to spy on private methods.

Can you use Jasmine to stub out a private method in an Angular component? The pattern I am using spies on specific providers - not components.

Can you stub out and spy on private methods in the component itself?

Or do I have to move the code out into a provider/service in order to stub it out?

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

describe('Component1', () => {
    let component: Component1;
    let fixture: ComponentFixture<Component1>;
    let component1ComponentSpy: any;

    beforeEach(async(() => {
        component1ComponentSpy = jasmine.createSpyObj('component1Component', ['logError']);
        component1ComponentSpy.logError = jasmine.createSpy().and.stub();
    }));

    it('should stub a private method', () => {      
        ConfigureTestingModule();       
    });

    function ConfigureTestingModule() {
        TestBed.configureTestingModule({
            declarations: [Component1],
            imports: [],
            providers: [
                { provide: Component1, useValue: component1ComponentSpy}
            ]
        }).compileComponents();
    
        fixture = TestBed.createComponent(Component1);
        component = fixture.componentInstance;
        fixture.detectChanges();
    }
});

import { Component, Input, OnInit, Renderer2 } from '@angular/core';

@Component({})

export class Component1 implements OnInit {
    constructor() { }

    ngOnInit(): void {}

    private logError(){}
}
Hoppe
  • 6,508
  • 17
  • 60
  • 114

0 Answers0