'Uncaught TypeError: Cannot convert undefined or null to object at store unit tests
I can't solve this problem Uncaught TypeError: Cannot convert undefined or null to object when I run unit tests. I don't know why I have got this error because data appear in subscribe. Can someone please help to fix it?
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;
}
});
}
spec.ts
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();
});
Thanks for help!
Solution 1:[1]
I think this line:
storeMock.select = () => of([fakeLocations] as any);
is causing the issue.
You are accessing the locations from an object:
this.store.select((state: IAppState): Locations => state.locations.locations);
So I am thinking you would have to provide an object like so.
Try this:
// storeMock.select = () => of([fakeLocations] as any);
storeMock.select.and.returnValue(of({ locations: { locations: of[fakeLocations] } }));
I think with the above, we will be mocking state.locations.locations correctly.
Edit I am thinking then this line is problematic:
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;
}
If the error goes away with the above line, then I am thinking item[key] is undefined or null and Object.values throws that error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
