Angular 使用组件ngOnInit时角度单元测试用例失败
我正在使用angular 7,在使用Angular 使用组件ngOnInit时角度单元测试用例失败,angular,jasmine,angular-unit-test,Angular,Jasmine,Angular Unit Test,我正在使用angular 7,在使用component.ngOnInit()和fixture.detectchanges()时无法运行单元测试用例。如果删除component.ngOnInit()和fixture.detectchanges()则测试用例通过,但我希望在spy之后检测更改 beforeEach(async(() => { TestBed.configureTestingModule({ imports: [AppTestingModule, Effe
component.ngOnInit()
和fixture.detectchanges()
时无法运行单元测试用例。如果删除component.ngOnInit()
和fixture.detectchanges()
则测试用例通过,但我希望在spy之后检测更改
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [AppTestingModule, EffectsModule.forRoot([NodeEffects])],
declarations: [SidenavComponent],
schemas: [NO_ERRORS_SCHEMA],
providers: [ApiNodesService]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SidenavComponent);
component = fixture.componentInstance;
browsingService = TestBed.get(BrowsingFilesService);
apiNodesService = TestBed.get(ApiNodesService);
appConfig = TestBed.get(AppConfigService);
// appConfigSpy = spyOn(appConfig, 'get').and.returnValue([navItem]);
});
it('check getDocLibraries method is called', () => {
spyOn(component, 'getDocLibraries');
fixture.detectChanges();
component.ngOnInit();
component.getDocLibraries();
fixture.whenStable().then(data => {
const debugUlElement = fixture.debugElement.query(By.css('ul.sidenav-menu_sub'));
const nativeUlElement: HTMLUListElement = debugUlElement.nativeElement;
expect(nativeUlElement.childElementCount).toEqual(1);
});
});
});
错误消息:
TypeError:无法将未定义或null转换为对象
在Function.keys()处
在SidenavComponent../src/app/components/sidenav/sidenav.component.ts.SidenavComponent.buildMenu(http://localhost:9876/src/app/components/sidenav/sidenav.component.ts?:93:19)
位于SidenavComponent../src/app/components/sidenav/sidenav.component.ts.SidenavComponent.ngonit(http://localhost:9876/src/app/components/sidenav/sidenav.component.ts?:76:28)
在UserContext。(http://localhost:9876/src/app/components/sidenav/sidenav.component.spec.ts?:103:15)
您应该将您的规范包装在异步
中,并在稳定时将检测更改移到内部
it('check getDocLibraries method is called', async(() => {
spyOn(component, 'getDocLibraries');
component.getDocLibraries();
fixture.whenStable().then(()=> {
fixture.detectChanges();
const debugUlElement = fixture.debugElement.query(By.css('ul.sidenav-menu_sub'));
const nativeUlElement: HTMLUListElement = debugUlElement.nativeElement;
expect(nativeUlElement.childElementCount).toEqual(1);
});
component.ngOnInit();
}));
注意:您有一个额外的'});'最后呢
您还可以使用fakeAsync&tick代替async&whenStable
it('check getDocLibraries method is called', fakeAsync(() => {
spyOn(component, 'getDocLibraries');
component.getDocLibraries();
component.ngOnInit();
tick();
fixture.detectChanges();
const debugUlElement = fixture.debugElement.query(By.css('ul.sidenav-menu_sub'));
const nativeUlElement: HTMLUListElement = debugUlElement.nativeElement;
expect(nativeUlElement.childElementCount).toEqual(1);
}));
尝试将“fixture.detectChanges()”移到fixture.whenStable()之前,可能会提供组件的代码?我已经添加了我收到的错误消息。