create test for activatedRoute data

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs/observable/of';
import { Observable } from 'rxjs/Observable';

import { MyComponent } from './my-component.component';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  const route = ({ data: of({ label: 'hello' }) } as any) as ActivatedRoute;

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [{ provide: ActivatedRoute, useValue: route }],
      }).compileComponents();
    }),
  );

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

  it('should set the label', () => {
    expect(component.label).toEqual('hello');
  });
});

The important thing to note here is that we are providing our own implementation of ActivatedRoute in TestBed.providers, with just one property (data) that is being used by our component.


In angular 8+ there is the RouterTestingModule, which you can use in order to have access to the ActivatedRoute or Router of the component. Also you can pass routes to the RouterTestingModule and create spies for the requested methods of route.

For example in my component I have:

ngOnInit() {
    this.data = this.route.data
}

And in my test I have:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ProductLinePageComponent ],
      schemas: [NO_ERRORS_SCHEMA],
      imports: [
        RouterTestingModule.withRoutes([])
      ],
    })
    .compileComponents()
  }))

  beforeEach(() => {
    router = TestBed.get(Router)
    route = TestBed.get(ActivatedRoute)
    route.data = hot('(a)', {a: someData})
  })

and later in the 'it' section:

  it('should update', () => {
    const spyRoute = spyOn(route.snapshot.paramMap, 'get')
    spyRoute.and.returnValue('21')
    fixture = TestBed.createComponent(ProductLinePageComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
    // here you can test the functionality which is triggered by route data
    const expected = cold('(a)', {a: someData})
    expect(component.data).toBeObservable(expected)
  })