我无法解决此问题未捕获类型错误:当我运行单元测试时,无法将未定义或null转换为对象。我不知道为什么我会出现这个错误,因为数据出现在订阅中。有人能帮我修一下吗?
ts
locations$ = this.store.select((state: IAppState): Locations => state.locations.locations);
getLocations(): void {
this.store.dispatch(GetLocations({ reset: this.reset }));
console.log(this.locations$)
this.locations$(here is an error).subscribe((item) => {
if (item) {
const key = 'content';
this.locations = Array.from(Object.values(item[key]));
this.reset = false;
}
});
}
规范
const storeMock = jasmine.createSpyObj('store', ['select', 'dispatch']);
storeMock.select = () => of([fakeLocations] as any);
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent,
...
],
imports: [
...
],
providers: [
...
{ provide: Store, useValue: storeMock }
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UbsAdminTariffsLocationDashboardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
router = TestBed.inject(Router);
httpMock = TestBed.inject(HttpTestingController);
});
it('should create', () => {
expect(component).toBeTruthy();
});
谢谢你的帮助!
我认为这一行:
storeMock.select = () => of([fakeLocations] as any);
是导致问题的原因。
您正在从一个对象访问位置:
this.store.select((state: IAppState): Locations => state.locations.locations);
所以我认为你必须提供一个这样的对象。
试试这个:
// storeMock.select = () => of([fakeLocations] as any);
storeMock.select.and.returnValue(of({ locations: { locations: of[fakeLocations] } }));
我认为通过以上内容,我们将正确地嘲笑state.locations.locations
。
编辑我认为这一行有问题:
if (item) {
const key = 'content';
// !! comment out below line and see if the error goes away
// this.locations = Array.from(Object.values(item[key]));
this.reset = false;
}
如果错误在上面的行中消失,那么我认为item[key]
是未定义的或null,Object.values抛出了这个错误。