0
0
Angularframework~30 mins

Testing routing and navigation in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing routing and navigation
📖 Scenario: You are building a simple Angular app with two pages: Home and About. You want to test that navigation between these pages works correctly.
🎯 Goal: Create a basic Angular routing setup with two routes, then write a test to check navigation from Home to About page.
📋 What You'll Learn
Create a standalone Angular component called HomeComponent with text 'Home Page'.
Create a standalone Angular component called AboutComponent with text 'About Page'.
Set up Angular routes for path '' to HomeComponent and path 'about' to AboutComponent.
Write a test that navigates from '' to 'about' and verifies the displayed text changes accordingly.
💡 Why This Matters
🌍 Real World
Routing is essential in Angular apps to switch views without reloading the page. Testing routing ensures users can navigate smoothly.
💼 Career
Many Angular developer roles require writing tests for routing to maintain app quality and prevent navigation bugs.
Progress0 / 4 steps
1
Create HomeComponent and AboutComponent
Create two standalone Angular components: HomeComponent that displays the text 'Home Page' inside a <h1> tag, and AboutComponent that displays the text 'About Page' inside a <h1> tag.
Angular
Need a hint?

Use @Component decorator with standalone: true and simple templates.

2
Set up Angular routes
Create a constant called appRoutes that is an array of routes. Add a route with path '' that loads HomeComponent, and a route with path 'about' that loads AboutComponent.
Angular
Need a hint?

Use Routes type and create an array with two route objects.

3
Configure RouterTestingModule with routes
In your test file, import RouterTestingModule and configure it with appRoutes. Create a test component that uses <router-outlet> to display routed components.
Angular
Need a hint?

Use RouterTestingModule.withRoutes(appRoutes) in the imports array of the test component.

4
Write a test to navigate and verify page content
Write a test that uses Angular's Router to navigate from the empty path '' to 'about'. Use fixture.detectChanges() and await router.navigate(['about']). Verify that the rendered text contains 'About Page'.
Angular
Need a hint?

Use await router.navigate(['about']) and then check the DOM text content.