0

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}},
];
Anonguy123
  • 407
  • 3
  • 16

1 Answers1

1

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.

Johns Mathew
  • 804
  • 5
  • 6
  • Thanks. Is it possible to make it optional so that it only uses `cached` when I specify in the test so that I can test both the `if` and `else`? If I do it this way it never goes into the `else` statement – Anonguy123 Sep 01 '19 at 21:21
  • You can modify the value of `mockActivatedRoute` before testing the `else` case - `mockActivatedRoute.snapshot.data.cached = false;` – Johns Mathew Sep 09 '19 at 06:31