Я начинаю с юнит-тестирования в Angular 9 с Жасмином.
Я тестирую простой компонент, который реализует ngOnInit
:
export class HomeComponent implements OnInit {
constructor(private router: Router
, private authenticationService: AuthenticationService) { }
ngOnInit(): void {
this.authenticationService.checkIsAuthenticatedObservable()
.subscribe(
(isAuthenicated: boolean) => {
if (isAuthenicated === true) {
this.router.navigate(['/observation-feed']);
}
});
}
}
Я сталкиваюсь с ошибкой при выполнении ловушки жизненного цикла ngOnInIt:
TypeError: Cannot read property 'subscribe' of undefined
at <Jasmine>
at HomeComponent.ngOnInit (http://localhost:9876/_karma_webpack_/main.js:8140:13)
Мой тест spe c настроен так:
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
let router: Router;
let mockAuthenticationService;
beforeEach(async(() => {
mockAuthenticationService = jasmine.createSpyObj(['checkIsAuthenticatedObservable']);
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([
// { path: 'login', component: DummyLoginLayoutComponent },
])
],
declarations: [ HomeComponent ],
providers: [
{ provide: AuthenticationService, useValue: mockAuthenticationService }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
router = TestBed.get(Router);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
mockAuthenticationService.checkIsAuthenticatedObservable.and.returnValue(of(false));
fixture.detectChanges();
// component.ngOnInit();
expect(component).toBeTruthy();
});
});
Я пробовал различные комбинации настройки фиктивного объекта и вызова fixture.detectChanges();
и component.ngOnInit();
в разных точках инициализации. Ничто из того, что я пробовал, не сработало. Что здесь не так?