I am unit testing a function in angular 4 project using jasmine which a switch statement like mentioned below:
switch(this.router.url) {
case 'firstpath': {
// some code
}
break;
case 'secondpath': {
// some more code
}
break;
default:
break;
}
In my spec.ts file. I can't stub or change the value of router.url.I want my cases to execute but default is executing. I tried different ways to set or spyOn and return value, but everytime url is '/'. Every suggestion or solution will be welcomed.
First you need to mock router in your testing module:
TestBed.configureTestingModule({
...
providers: [
{
provide: Router,
useValue: {
url: '/path'
} // you could use also jasmine.createSpyObj() for methods
}
]
});
You can also change the url in the test and run your tested method:
const router = TestBed.get(Router);
router.url = '/path/to/anything';
// now you can run your tested method:
component.testedFunction();
As you mention spyOn
doesnt work because it works only for methods/functions. But url
is a property.