Sitemap

Devlog #2

Routes, Bloody Routes

2 min readJul 24, 2018

--

Today I wrote a test spec for an Angular component that interacted with the router. This is always painful. The simple way to do it in a unit test is to provide a mock Router instance and a mock ActivatedRoute via the test-bed, and configure them with the necessary params and data to initialise the component.

But what if some element in your component’s template makes use of the [routerLink]="expression" directive, and you want to test it navigates a correctly calculated URL when somebody clicks on it? You could try it like this:

element.nativeElement.querySelector('a').click()
const router = TestBed.get(Router);
expect(router.navigate).toHaveBeenCalledWith(['new-page', 123]);

However, mocking Router in such a way that instances of the routerLink directive will work is not easy or obvious, and even if we could do it, it would break if routerLink was changed in future to internally use some part of Router that we haven’t mocked.

Fortunately, Angular provides a module RouterTestingModule that provides a version of Router that works inside a test. Now you can go:

element.nativeElement.querySelector('button.go').click()
tick();
expect(router.url).toEqual('/new-page/123');

However, this module is intended for a integration testing, not unit testing, and so provides no way to easily setup initial ActivatedRoute data, and has no concept of a pseudo-navigation to a non-configured route. Also, if you provide an ActivatedRoute of your own, you will break the navigation, meaning you can’t check use router.url to check the updated URL.

Get Jon Rimmer’s stories in your inbox

Join Medium for free to get updates from this writer.

The only way I’ve found around this is to write the test as a full integration test, which means creating dummy and container components and a simplified route configuration.

@Component({ template: '<router-outlet></router-outlet' })
class TestWrapperComponent
@Component({ template: '' })
class DummyComponent
TestBed.configure({
imports: [
RouterTestingModule.withRoutes([{
path: '',
component: TestWrapperComponent,
children: [
{ path: '', component: ComponentUnderTest },
{ path: 'new-page/:id', component: DummyComponent }
]
}])
]
});
const router = TestBed.get(Router);
router.navigateByUrl('/');

Now you will actually get a “real” router setup. The router will render ComponentUnderTest into the router-outlet inside the wrapper component. You can then get the component instance using the fixture andBy.directive() . Then, when you click something, an actual navigation will be performed (to the DummyComponent route, for example), and you can test it by checking router.url.

It’s quite a bit of effort to go just to check that clicking something is navigating correctly. Is it worth it? Hmm. I’ll get back to you on that.

--

--