Testing Routes
Learn how to test routing between components.
When we test routing in an Angular application, we want to check that our component calls the Router
with the correct route and parameters. For example, when the user clicks on a link, we could check if the component
redirects the user to the correct URL. We can achieve this by providing our TestBed
with a mock of the Angular Router
.
The simplest way to mock the Router
is to use Jasmine to create our own mock object and spy on the navigateByUrl
method. This is a flexible solution and lets us test simple cases.
For more complicated cases, we can use the RouterTestingModule
provided by Angular. Although the RouterTestingModule
takes some work to configure, it allows us to test components with more complicated interactions with the Router
.
Using Jasmine to spy on the Router
We can use Jasmine to mock the Router
's navigateByUrl
method. This allows us to intercept redirect requests and make expectations about the arguments passed to the Router
.
let fakeRouter = jasmine.createSpyObj('Router', ['navigateByUrl']);
Here, we use Jasmine’s createSpyObj
method to create a spy of the Router
class mocking the navigateByUrl
method. We can now provide this spy object to the TestBed
when we set up our test, as shown below:
beforeEach(async () => {TestBed.configureTestingModule({providers: [{ provide: Router, useValue: fakeRouter }],declarations: [MyComponent]}).compileComponents();});
Now, in our test, we can simulate an action that should lead to a routing event. For example, we can simulate the user clicking on a RouterLink
element. Then, we can use the spy to verify that the Router
was called with the correct URL ...