Search code examples
angularunit-testingdependency-injection

How to access private service which is provided by the component itself for unit testing


I have this component which provides a service by itself

@Component({
    selector: 'my-component',
    providers: [MyService],
    ...
})
export class MyComponent { 
  constructor(@Self() private service: MyService) {}
  ...
}

During unit testing I noticed the following

beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [MyService],
    }).compileComponents();
    service = TestBed.inject(MyService);
});

That service is not the same instance as the service inside my component. I guess this makes sense, but I cannot find a solution for this, because for my tests I need access to that service inside my component. Any suggestions?


Solution

  • As mentioned in the comments above by @johnrsharpe its implementation detail so you shouldn't have to deal with it. Which is what I did, but I just found a way to do it. I don't need it anymore, but just for educational purposes I'll show it anyway:

    let myService: MyService;
    
    beforeEach(() => {
        myService = { ... };
    
        TestBed.configureTestingModule({
            declarations: [MyComponent],
            providers: [MyService],
        }).overrideComponent(MyComponent, {
            set: {
                providers: [
                    provide: MyService, useValue: myService
                ]
            }
        });
    }).compileComponents();
    

    Now you can use myService for mocking and spying!