Reputation: 3272
I want to be able to test the param being passed from one view to the other. I want to test to see if the param is there and that the param matches the mock test data I give it.
I'm quite new to unit tests, done a lot of reading into setting up the test in respect to the activated route and passing a param. I think the bit I am stuck on is the "expect". Its giving me an error
Argument of type '{ urn: string[]; }' is not assignable to parameter of type 'Expected<Observable<Params>>'
component
export class SearchComponent implements OnInit {
constructor(private route: ActivatedRoute, private router: Router) {
this.getParam();
}
ngOnInit() {
}
getParam():void {
this.route.queryParams.subscribe(params => {
console.log(params["urn"]);
});
}
}
spec
providers: [
HttpClient,
{
provide: ActivatedRoute,
useValue: {
queryParams: of({
urn: '123'
})
}
}
],
...
it('test queryParam in route', () => {
const activatedRoute: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
activatedRoute.queryParams = of({ urn: '123' });
fixture.detectChanges();
// tick();
expect(activatedRoute.queryParams).toEqual({ urn: ['123'] }); // this line giving me trouble
});
If anybody can give me a hand to see what I am doing wrong - here is the stackBlitz I came up with to demo
Upvotes: 3
Views: 11045
Reputation: 373
Adding since this was the top result when searching angular test query params jest
If you are using const { params: { id } } = this.route.snapshot
in your component. You should also define your mockActivatedRoute
containing snapshot
property
const mockActivatedRoute = { snapshot: { params: of({ id: 'test-id' })} };
otherwise you might get an error similar to TypeError: Cannot read property 'params' of undefined
Upvotes: 0
Reputation: 31263
Here :
expect(activatedRoute.queryParams).toEqual({ urn: ['123'] })
activatedRoute.queryParams
is not { urn: ['123'] }
but an Observable
that will fire this value.
You can test it like this :
/*
Notice the extra "done" parameter. It is a function that you must call
to indicate that the test is finished.
It is necessary because we are testing an asynchronous method.
This will prevent the test from exiting until the "done" method is called.
Also, the test will fail if the done method is not called within 5s by default.
*/
it('test queryParam in route', (done) => {
[...]
activatedRoute.queryParams.subscribe((value) => {
expect(value).toEqual({ urn: ['123'] })
done();
})
});
Upvotes: 4