Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The process for mocking ActivatedRoute involves creating a spy object for the ActivatedRoute service, setting up mock data for the route parameters or query parameters, and providing the spy object in the component's testbed configuration.

Here are the steps:

  1. Import the ActivatedRoute service and create a spy object for it:
import { ActivatedRoute, Params } from '@angular/router';
import { of } from 'rxjs';

class ActivatedRouteStub {
  queryParams = of({});
  paramMap = of({});
}
  1. Set up mock data for the route parameters or query parameters:
const mockParams = { id: 1 };
const mockQueryParams = { filter: 'completed' };
  1. Provide the spy object in the component's testbed configuration:
beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [MyComponent],
    providers: [
      { provide: ActivatedRoute, useClass: ActivatedRouteStub }
    ]
  })
  .compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;

  const activatedRoute = TestBed.get(ActivatedRoute);
  activatedRoute.queryParams = of(mockQueryParams);
  activatedRoute.paramMap = of(mockParams);
});
  1. Use the mock data in your component's ngOnInit() or constructor:
constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.queryParams.subscribe(params => {
    console.log(params.filter); // will output 'completed'
  });

  this.route.paramMap.subscribe(params => {
    console.log(params.get('id')); // will output '1'
  });
}