Reputation: 5711
I'm using activated route to listen route data changes:
this.activatedRoute.params.subscribe(params => {
this.model.load(params['id']);
});
In my unit test I want to mock this part this.activatedRoute.params.subscribe
to provide test data:
mockActivatedRoute.params = jasmine.createSpy('mockActivatedRoute.params')
.and
.returnValue(Observable.of(<Params>{id: 1}));
But I'm getting an error:
Type 'Spy' is not assignable to type 'Observable'. Property '_isScalar' is missing in type 'Spy'
What does this error mean? I'm using similar arrroach for other observers and everething works fine, but only this place.
Upvotes: 1
Views: 7299
Reputation: 596
Hopefully this can help someone like me. Adding to AngularChef's answer, I had a chain like this:
// component.ts
this.route.paramMap
.flatMap((paramMap: Params) => {
return paramMap.params['userId'];
})
.flatMap((userId: string) => {
...
}
.subscribe(whatever)...
And I couldn't mock it right from the module declaration because I need to test the component's response to different userId
s coming from paramMap
.
So just spying on the flatMap
call from route.paramMap
saved me a lot of lines.
// component.spec.ts
import { of } from 'rxjs';
//...
let route: ActivatedRoute;
// ...
route = TestBed.get(ActivatedRoute);
spyRoute = spyOn(route.paramMap, 'flatMap').and.returnValue(
of(profileId), // notice this is just the string the next chain asks for
);
Upvotes: 2
Reputation: 21
Tested working in Angular 4
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Rx';
...
class MockActivatedRoute extends ActivatedRoute {
public params = Observable.of({id: 123});
}
...
describe('MyTest', () => {
...
beforeEach(async(() => {
TestBed.configureTestingModule({
...
providers: [ { provide: ActivatedRoute, useValue: new MockActivatedRoute() } ]
})
.compileComponents();
}));
});
Upvotes: 0
Reputation: 14087
How about you try to spy on the params.subscribe()
method instead of the params
property?
Something along the lines of:
// This code might need some adjustments...
class MockActivatedRoute {
params = {
subscribe: jasmine.createSpy('subscribe')
.and
.returnValue(Observable.of(<Params>{id: 1}))
}
}
Upvotes: 3