Punj324
Punj324

Reputation: 265

jasmine angular 4 unit test router.url

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.

Upvotes: 22

Views: 38485

Answers (2)

Martin Nuc
Martin Nuc

Reputation: 5764

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.inject(Router);
// @ts-ignore: force this private property value for testing.
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.

Upvotes: 41

PeterS
PeterS

Reputation: 2954

For people using Angular 9 and above property url is now a readonly property and so spyOnProperty will not work. It's also confusing as you won't get an error, but you won't see any "spying" either.

To solve this, use the following code:

const mockUrlTree = routerSpy.parseUrl('/mynewpath/myattribute');
// @ts-ignore: force this private property value for testing.
routerSpy.currentUrlTree = mockUrlTree;

Thanks to Rob on this post here for the answer:

https://stackoverflow.com/a/63623284/1774291

Upvotes: 8

Related Questions