3

I have an angular 6 application and I am trying to unit test a component where I inject the Router. In my ngOnInit method I reference this.router.url and work with it.

So now I am attempting to write a jasmine unit test and I cannot set the router.url property because it "is a constant ot read only property". I am currently mocking the router like this.

mockRouter = jasmine.createSpyObj<Router>("router", ["navigate", "navigateByUrl"]);

What else do I need to set to properly mock the url value in my test?

user1247395
  • 409
  • 1
  • 9
  • 20

2 Answers2

8

Jasmine spy on property should be reasonable solution

spyOnProperty(router, 'url', 'get').and.returnValue('/users');

as recommended here https://stackoverflow.com/a/43793575/11552394

and documented in Jasmine docs https://jasmine.github.io/api/3.4/global.html#spyOnProperty

Alex Karamushko
  • 151
  • 2
  • 5
  • 4
    i am getting url property dosn't exist error. Note: url is a read-only property, does it have any effect on spyOnProperty() behavior ? – Rkmr039 Aug 17 '20 at 13:56
  • define your router object after your describe. then this is what worked for me: beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: Router, useValue: { url: '/page1', events: of(new NavigationEnd(0, '/page1', '/')), navigate: jasmine.createSpy('navigate'), }, }, ], imports: [RouterTestingModule], }).compileComponents(); router = TestBed.inject(Router); MockRender(); }); – reinaH Jul 18 '23 at 03:50
0

this is what worked for me:

describe('Yourserviceorcomponent', () => {

...

let router: Router;

...

beforeEach(() => {
TestBed.configureTestingModule({
  providers: [
    {
      provide: Router,
      useValue: {
        url: '/page1',
        events: of(new NavigationEnd(0, '/page1', '/')),
        navigate: jasmine.createSpy('navigate'),
      },
    },
  ],
  imports: [RouterTestingModule],
}).compileComponents();

router = TestBed.inject(Router);

MockRender();
});
...
});
reinaH
  • 534
  • 6
  • 10