Using Jasmine framework to test Angular Router

Have an Angular application that uses the @angular/router to provide navigation across pages?

The following test sample could be scaled to your application to ensure routing is done correctly, from one component to another.

First of all, let’s import the dependencies we will need in this test:

import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { Component, NgModule } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Routes } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';

Then, let’s create a TestBootstrapComponent which contains the router-outlet — used to bootstrap the test app; and a TestComponent.

You won’t need to create different components for each route. A dummy test component is more than enough.

@Component({ template: '<router-outlet></router-outlet>' })
class TestBootstrapComponent {}
@Component({ template: '' })
class TestComponent {}

Now, you will need to import these components to the app.

Keeping in mind that components can only be imported by one module, you should create a shared module and import components there — which could be imported by any feature modules in case of need:


@NgModule({
declarations: [TestComponent,TestBootstrapComponent],
imports: [RouterTestingModule]
})
class TestSharedModule { }

And then, you’ll need to provide routes:

const testRoutes: Routes = [
{
path: '',
children: [
{
path: '',
component: TestComponent
},
{
path: 'about',
component: TestComponent
}
]
},
{
path: 'change-language/:languageCode',
component: TestComponent
},
{
path: '**',
redirectTo: '',
pathMatch: 'full'
}
];

Finally, it’s time to prepare the module configuration for testing purposes:


// test module configuration for each test
const testModuleConfig = () => {
// reset the test environment before initializing it.
TestBed.resetTestEnvironment();
  TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting())
.configureTestingModule({
imports: [
TestSharedModule,
RouterTestingModule.withRoutes(testRoutes),
]
});
};

After all, testing the route navigation across pages is as easy as below:

describe('Some service',
() => {
beforeEach(() => {
testModuleConfig();
});
  it('should be able to navigate to `/`',
fakeAsync(() => {
const injector = getTestBed();
const router = injector.get(Router);
      const fixture = TestBed.createComponent(TestBootstrapComponent);
fixture.detectChanges();
      // initial navigation
router.navigate(['/'])
.then(() => {
expect(router.url).toEqual('/');
});
}));
});

Burak Tasci (fulls1z3)
https://www.linkedin.com/in/buraktasci
http://stackoverflow.com/users/7047325/burak-tasci
https://github.com/fulls1z3

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.