Reputation: 406
Lets say I have a subscription to route params in my component:
this.route.params.subscribe((params) => {
// what the params object holds
// params.id1 params.id2
// what the current route looks like
//localhost/params.id1/params.id2
});
How would I unit test params.id2
in Angular? Example: i want to test if params.id2 > 0
Currently I have done this:
// top of the describe
let route: ActivatedRoute;
//inside the TestBed.configureTestingModule
providers: [
{
provide: ActivatedRoute,
useValue: {
params: of({
id1: 1,
id2: 0,
}),
},
},
],
route = TestBed.inject(ActivatedRoute);
it('shouldn't be zero', () => {
// i want to check if params.id2 is not zero
expect(params.id2).not.toBe(0);
});
I don't have any experience using unit tests. Do i have to subscribe to the route.params like i do in the component, or how do i implement the test method?
Upvotes: 2
Views: 9332
Reputation: 18899
It will be zero because you're providing a static value of zero in the useValue
.
To be able to change it, I would use a BehaviorSubject
where it is an observable and it can be changed in the future by using next
.
import { BehaviorSubject } from 'rxjs';
....
// top of the describe
let route: ActivatedRoute;
const paramsSubject = new BehaviorSubject({
id1: 1,
id2: 0,
});
//inside the TestBed.configureTestingModule
providers: [
{
provide: ActivatedRoute,
useValue: {
params: paramsSubject
},
},
]
route = TestBed.inject(ActivatedRoute);
it('should be zero', (done) => { // add done to let Jasmine know when you're done with the test
route.params.subscribe(params => {
expect(params.id2).toBe(0);
done();
});
});
it('should not be zero', (done) => {
paramsSubject.next({ id1: 1, id2: 3});
route.params.subscribe(params => {
expect(params.id2).not.toBe(0);
done();
});
});
But ideally those tests written are not good. You should be testing what happens inside of the subscribe
in your component and assert that what happens does indeed happen.
Upvotes: 8