So I'm trying to write a test on a component that does not have a lifecycle hook.
The problem is I do not know when assigning a value directly like this without a lifecycle hook I do not know when it is exactly called and why it is not called on the component initialization
component.ts
export class MainNavComponent {
isLoggedIn: boolean = this.authService.isLoggedIn;
user: User;
isHandset$: Observable<boolean> =
this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => result.matches)
);
constructor(private breakpointObserver: BreakpointObserver,
public authService: AuthService) {
//check logged in user
this.authService.user$.subscribe(res => {
if(res) {
this.isLoggedIn = true;
this.user = res;
} else {
this.isLoggedIn = false;
}
})
}
}
component.spec.ts
describe('MainNavComponent', () => {
let component: MainNavComponent;
let fixture: ComponentFixture<MainNavComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MainNavComponent,
FooterComponent
],
imports: [
MaterialImportsModule,
RouterTestingModule.withRoutes([]),
HttpClientModule,
AngularFireModule.initializeApp(environment.firebase, 'my-app-name'),
AngularFirestoreModule,
AngularFireStorageModule,
AngularFireAuthModule,
BrowserAnimationsModule
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MainNavComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('assing return if user is logged in and assign it to isLoggedIn', () => {
let service: AuthService = TestBed.get(AuthService);
spyOn(service, 'isLoggedIn').and.returnValue(true);
expect(component.isLoggedIn).toBeTruthy();
});
});
Logged message
Expected false to be truthy.