简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM