Sarat
Sarat

Reputation: 131

Angular 4 - router.url unit testing

How do I mock router.url in angular 4 unit testing?

I use router.url in ngOnint in my component but in my test the value for router.url is '/'

Upvotes: 10

Views: 9901

Answers (4)

ConorJohn
ConorJohn

Reputation: 667

I have had to move from some of the suggested solutions used here during my migration to Angular 17. Inside the TestBed Configuration, provide some test routes:

imports: [
    RouterTestingModule.withRoutes([
      { path: '', component: YourComponent },
      { path: 'page', component: YourComponent },
      { path: 'page/fail', component: YourComponent },
      { path: 'etc', component: YourComponent },
      { path: '**', redirectTo: '' }
    ])
  ]

Then in your actual test, it can be configured as the following:

it('should return true if url ends with page', async () => {
  // Arrange
  const expected = true;
  await component['router'].navigate(['page']);

  // Act
  const actual = component.isPage();

  // Assert
  expect(actual).toEqual(expected);
});

This may not be ideal, but now that the properties we have been relying on until now are readonly, I'm not aware of any other path forward for the moment.

Upvotes: 0

Rob
Rob

Reputation: 3746

In Angular v9 Router.url is a readonly getter property. You can force the private property value to set the url property:

    const mockUrlTree = router.parseUrl('/heroes/captain-marvel');
    // @ts-ignore: force this private property value for testing.
    router.currentUrlTree = mockUrlTree;

Upvotes: 19

Mohamed Farouk
Mohamed Farouk

Reputation: 1107

This sounds like a solution jasmine angular 4 unit test router.url

const router = TestBed.get(Router);
router.url = '/path/to/anything';
// now you can run your tested method:
component.ngOnint();

Upvotes: -2

kodeaben
kodeaben

Reputation: 2055

you could use jasmine spyObj. In you TestBed:

providers:[
 {
 provide: Router,
 usevalue: jasmine.createSpyObj('Router',['methodOne','methodTwo]),
 },
],

in beforeEach:

router = fixture.debugElement.injector.get(Router);

in the test:

it('should...', ()=> {
 (router.methodOne as Spy).and.returnValue(whateverValue)// if you wanna mock the response
});

Upvotes: 3

Related Questions