【发布时间】:2020-03-18 20:57:02
【问题描述】:
我开始使用 Jasmine 在 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)
我的测试规范是这样设置的:
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();。我所尝试的都没有奏效。这里出了什么问题?
【问题讨论】: