I tried write tests for my angular component which is using service. I initialized my userServiceStub property isLoggedIn with true, but when I run tests components UserService property is false. I tried remove Injectable() decorator and change anonymous object to UserService.
Tests
import { async, ComponentFixture, ComponentFixtureAutoDetect, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { WelcomeComponent } from './welcome.component';
import { UserService, User } from './model';
class UserServiceMock{
isLoggedIn: boolean = true;
user: User = {name: 'Mock user'};
}
describe('Welcome component tests', () =>{
let component: WelcomeComponent;
let fixture: ComponentFixture<WelcomeComponent>;
let debugElment: DebugElement;
let htmlElement: HTMLElement;
let userService: UserService;
let userServiceStub: {
isLoggedIn: boolean;
user: { name: string }
};
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [WelcomeComponent],
})
.overrideComponent(WelcomeComponent, {
set: {
providers: [
{provide: UserService, useClass: UserServiceMock}
]
}
})
.compileComponents()
.then(() =>{
fixture = TestBed.createComponent(WelcomeComponent);
component = fixture.componentInstance;
userService = TestBed.get(UserService);
console.log(userService);
debugElment = fixture.debugElement.query(By.css('.welcome'));
htmlElement = debugElment.nativeElement;
});
});
it('stub object and injected UserService should not be the same', () =>{
expect(userServiceStub === userService).toBe(false);
});
it('changing the stub object has no effect on the injected service', () =>{
userServiceStub.isLoggedIn = false;
expect(userService.isLoggedIn).toBe(true);
});
it('should welcome user', () => {
fixture.detectChanges();
const content = htmlElement.textContent;
expect(content).toContain('Welcome');
})
})
Welcome Component
import { Component, OnInit } from '@angular/core';
import { UserService } from './model';
@Component({
selector: 'app-welcome',
template: '<h3 class="welcome" ><i>{{welcome}}</i></h3>',
providers: [UserService]
})
export class WelcomeComponent implements OnInit {
welcome: string = '-- not initialized yet --';
constructor(private userService: UserService) { }
ngOnInit(): void {
this.welcome = this.userService.isLoggedIn ?
'Welcome, ' + this.userService.user.name :
'Please log in.';
}
}
User Service
import { Injectable } from '@angular/core';
@Injectable()
export class UserService {
isLoggedIn: boolean;
user: User;
}
export class User{
name: string;
}
Failed test result link
My question is: How to correctly inject service?