How to Fake a Route Change in an Angular Unit Test

This isn't something that's come up too often in my experience with Angular, but sometimes I've needed to write code that subscribes to Router.events and takes action based on the current route.

But how do you test something like that in a unit test? The key is by using a Subject, which is a kind of Observable, and exposes a next() method, which allows us to simulate a route change. Here's an example:

    const event = new NavigationEnd(1703, `/account/orders/${orderId}`, '/');
    (router.events as Subject<Event>).next(event);

By casting Router's events property as a Subject, we can call next() with our NavigationEnd event, and simulate the route change.

For the Event type, make sure you are importing Event from @angular/router.

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4