Bird
Raised Fist0
Angularframework~20 mins

Testing routing and navigation in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Routing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when navigating to a non-existent route?
Given an Angular app with a routing module that defines routes for /home and /about, what will be the rendered output if the user navigates to /contact?
Angular
const routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '**', component: NotFoundComponent }
];
AThe <code>NotFoundComponent</code> is rendered showing a 404 message.
BThe app crashes with a routing error.
CThe <code>HomeComponent</code> is rendered by default.
DNothing is rendered and the page stays blank.
Attempts:
2 left
💡 Hint
Look at the wildcard route ** in the routes array.
state_output
intermediate
2:00remaining
What is the value of router.url after navigation?
In an Angular component, after calling router.navigate(['/profile', 42]), what will router.url contain?
Angular
constructor(private router: Router) {}

async navigateToProfile() {
  await this.router.navigate(['/profile', 42]);
  console.log(this.router.url);
}
A'/profile/undefined'
B'/profile/42'
C'/profile'
D'/profile?id=42'
Attempts:
2 left
💡 Hint
Check how path parameters are passed in the navigate method.
🔧 Debug
advanced
2:00remaining
Why does this test fail when checking navigation?
Consider this Angular test snippet:
it('should navigate to dashboard', () => {
  const router = TestBed.inject(Router);
  const spy = spyOn(router, 'navigate');
  component.goToDashboard();
  expect(spy).toHaveBeenCalledWith(['/dashboard']);
});
The test fails because spyOn is never called. Why?
Angular
goToDashboard() {
  this.router.navigateByUrl('/dashboard');
}
AThe router is not injected properly in the test.
BThe spy is set after the method call, so it misses the call.
CThe test should use <code>fakeAsync</code> to detect navigation calls.
DThe component calls <code>navigateByUrl</code> but the spy watches <code>navigate</code>, so the spy is not triggered.
Attempts:
2 left
💡 Hint
Check which router method is called in the component versus which is spied on.
📝 Syntax
advanced
2:00remaining
Which option correctly mocks ActivatedRoute with query params in a test?
You want to test a component that reads query parameters from ActivatedRoute. Which mock setup is correct?
A{ provide: ActivatedRoute, useValue: { queryParams: { search: 'test' } } }
B{ provide: ActivatedRoute, useValue: { queryParams: new BehaviorSubject({ search: 'test' }) } }
C{ provide: ActivatedRoute, useValue: { queryParams: of({ search: 'test' }) } }
D{ provide: ActivatedRoute, useValue: { queryParams: () => ({ search: 'test' }) } }
Attempts:
2 left
💡 Hint
Remember that queryParams is an Observable in Angular.
🧠 Conceptual
expert
2:00remaining
What is the main benefit of using RouterTestingModule in Angular tests?
Why should you use RouterTestingModule instead of RouterModule in Angular unit tests that involve routing?
ARouterTestingModule provides a simplified router setup that avoids real navigation and allows mocking routes easily.
BRouterTestingModule automatically runs all routes in a real browser environment during tests.
CRouterTestingModule disables routing completely to speed up tests.
DRouterTestingModule replaces the router with a synchronous version that blocks until navigation completes.
Attempts:
2 left
💡 Hint
Think about how tests should avoid side effects like real navigation.

Practice

(1/5)
1. What is the main purpose of using RouterTestingModule in Angular tests?
easy
A. To style the router links in the application
B. To disable routing completely in tests
C. To create real HTTP requests during navigation
D. To simulate routing behavior without starting the full app

Solution

  1. Step 1: Understand the role of RouterTestingModule

    RouterTestingModule is designed to simulate routing in tests without launching the full Angular app.
  2. Step 2: Compare options with this purpose

    Styling the router links is incorrect. Creating real HTTP requests during navigation is wrong. Disabling routing completely is incorrect. Simulating routing behavior without starting the full app correctly describes this testing utility.
  3. Final Answer:

    To simulate routing behavior without starting the full app -> Option D
  4. Quick Check:

    RouterTestingModule simulates routing [OK]
Hint: RouterTestingModule simulates routes in tests, not real navigation [OK]
Common Mistakes:
  • Thinking RouterTestingModule styles links
  • Assuming it sends real HTTP requests
  • Believing it disables routing
2. Which of the following is the correct way to import RouterTestingModule in an Angular test file?
easy
A. import { RouterTestingModule } from '@angular/router/testing';
B. import { RouterTestingModule } from '@angular/core/testing';
C. import { RouterTestingModule } from '@angular/router';
D. import { RouterTestingModule } from '@angular/testing/router';

Solution

  1. Step 1: Recall the correct import path

    The RouterTestingModule is provided by the '@angular/router/testing' package.
  2. Step 2: Verify each option's path

    Only import { RouterTestingModule } from '@angular/router/testing'; uses the correct path '@angular/router/testing'. Others are incorrect or do not exist.
  3. Final Answer:

    import { RouterTestingModule } from '@angular/router/testing'; -> Option A
  4. Quick Check:

    Correct import path is '@angular/router/testing' [OK]
Hint: RouterTestingModule always imports from '@angular/router/testing' [OK]
Common Mistakes:
  • Importing from '@angular/core/testing'
  • Importing from '@angular/router'
  • Using a non-existent path
3. Given this test snippet, what will location.path() return after navigation?
const fixture = TestBed.createComponent(AppComponent);
const router = TestBed.inject(Router);
const location = TestBed.inject(Location);
router.navigate(['/dashboard']);
fixture.detectChanges();
await fixture.whenStable();
console.log(location.path());
medium
A. "/"
B. "/dashboard"
C. "/home"
D. "undefined"

Solution

  1. Step 1: Understand navigation and location.path()

    Calling router.navigate(['/dashboard']) changes the URL path to '/dashboard'. The Location service reflects this path.
  2. Step 2: Confirm location.path() after navigation

    After navigation and stabilization, location.path() returns the current URL path, which is '/dashboard'.
  3. Final Answer:

    "/dashboard" -> Option B
  4. Quick Check:

    location.path() shows current URL path [OK]
Hint: location.path() returns the current URL after navigation [OK]
Common Mistakes:
  • Expecting location.path() to be '/' by default
  • Confusing location.path() with component state
  • Not awaiting navigation completion
4. Identify the error in this test setup for routing:
beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [RouterTestingModule],
    declarations: [AppComponent]
  });
  router = TestBed.inject(Router);
  location = TestBed.inject(Location);
  fixture = TestBed.createComponent(AppComponent);
  router.navigate(['/profile']);
  fixture.detectChanges();
});
medium
A. router.navigate() must be called after fixture.detectChanges()
B. RouterTestingModule should not be imported in tests
C. Missing call to compileComponents() before creating the component
D. Location service cannot be injected in tests

Solution

  1. Step 1: Check Angular test setup best practices

    When using TestBed with components, compileComponents() must be called to compile templates before creating components.
  2. Step 2: Analyze the given code

    The code configures the module but does not call compileComponents(), which can cause errors when creating the component.
  3. Final Answer:

    Missing call to compileComponents() before creating the component -> Option C
  4. Quick Check:

    Always call compileComponents() before createComponent() [OK]
Hint: Always call compileComponents() before createComponent() in tests [OK]
Common Mistakes:
  • Skipping compileComponents() causes template errors
  • Thinking RouterTestingModule is not needed
  • Calling navigate() before detectChanges() is allowed
5. You want to test that navigating to /settings loads the SettingsComponent. Which approach correctly tests this behavior?
hard
A. Use RouterTestingModule with routes, navigate to '/settings', then check if the component instance is of type SettingsComponent
B. Manually create SettingsComponent and call its ngOnInit without routing
C. Use RouterTestingModule but do not define routes, then navigate to '/settings'
D. Navigate to '/settings' without RouterTestingModule and check the URL

Solution

  1. Step 1: Set up RouterTestingModule with route definitions

    To test navigation, RouterTestingModule must be configured with routes linking '/settings' to SettingsComponent.
  2. Step 2: Navigate to '/settings' and verify component

    After navigation, verify the loaded component instance is SettingsComponent to confirm correct routing.
  3. Final Answer:

    Use RouterTestingModule with routes, navigate to '/settings', then check if the component instance is of type SettingsComponent -> Option A
  4. Quick Check:

    Define routes and check component after navigation [OK]
Hint: Define routes in RouterTestingModule to test navigation and component loading [OK]
Common Mistakes:
  • Not defining routes in RouterTestingModule
  • Testing component without routing
  • Checking URL without verifying component