Search code examples
angularangular2-testing

How to test if statement in ngOnInit that depends on route param


My Angular 8 web app has one component that does different things depending on the route. In ngOnInit I use route data to check if the cached param is present. I am trying to write a unit test that sets cached to be true so it goes into the if statement in ngOnInit but its not working. What am I doing wrong?

home.component.ts

cached = false;

constructor(private backend: APIService, private activatedRoute: ActivatedRoute) { }

ngOnInit() {
  this.cached = this.activatedRoute.snapshot.data['cached']; 
  if (this.cached)
  {
    this.getCached();
  }
  else
  {
    this.fetchFromAPI();
  }
}

home.component.spec.ts

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let service: APIService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
      ],
      declarations: [
        HomeComponent,
      ],
      providers: [
        APIService
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    service = TestBed.get(APIService);
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

   it('should go into if cached statement', fakeAsync(() => {
    component.cached = true;
    component.ngOnInit();
    const dummyData = [
      { id: 1, name: 'testing' }
    ];

    spyOn(service, 'fetchCachedData').and.callFake(() => {
      return from([dummyData]);
    });

    expect(service.fetchCachedData).toHaveBeenCalled();
  }));

})

router module

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'view-cache', component: HomeComponent, data: {cached: true}},
];

Solution

  • You can mock ActivatedRoute in your tests. Create an object with the value you need in ActivatedRoute in your spec file.

    const mockActivatedRoute = {
      snapshot: {
        data: {
          cached: true
        }
      }
    }
    

    In TestBed.configureTestingModule, provide this value instead of ActivatedRoute. Modify your providers as below:

    providers: [
        APIService,
        { provide: ActivatedRoute, useValue: mockActivatedRoute }
    ]
    

    Now your component would be using this mock value for ActivatedRoute during unit tests.