Pritam Bohra
Pritam Bohra

Reputation: 4319

Jasmine+Karma: ActivatedRoute spy not not getting called

I have an Angular component that uses ActivateRoute

getFlavorAndService(): void {
    this._route.params.subscribe(params => {

      const flavor: string = params.flavor;
      const service: string = params.service;
      const platform: string = params.platform;

      if (platform) {
        this.platform = platform;
      } else {
        this.platform = this._dataService.DEFAULT_PLATFORM;
      }

      if (flavor) {
        this.flavor = flavor;
      } else {
        this.flavor = this._dataService.DEFAULT_FLAVOR;
      }

      if (service) {
          this.service = service;
      } else {
        this.service = this._dataService.DEFAULT_SERVICE;
      }
    });
  }

I am trying to test getFlavorAndService() method in the following way:

it('Test', () => {

      dataService.attributeSearchEnabled = false;
      dataService.endpointSearchEnabled = false;

      const spy = spyOn(activatedRoute, 'params').and.returnValue(of({
        flavor: 'by-fund',
        service: 'profile_benchmarks',
        platform: 'on-prem',
      }));

      component.getFlavorAndService();

      expect(spy).toHaveBeenCalled();

      expect(component.platform).toBe('on-prem');
      expect(component.service).toBe('profile_benchmarks');
      expect(component.flavor).toBe('by-fund');
    });

I have also created a stub for ActivatedRoute:

class ActivatedRouteStub {

  get params() {
    return of({});
  }

  get queryParams() {
    return of({});
  }
}

My test cases are failing and none of the expectations are working fine. flavor, service and platform are taking the default values provided in the class and not the values passed using spyOn(activatedRoute, 'params').and.returnValue(of({....

I have also provided ActivatedRouteStub in the TestBed.configureTestingModule method

{ provide: ActivatedRoute, useClass: ActivatedRouteStub }

Upvotes: 0

Views: 246

Answers (1)

robert
robert

Reputation: 6142

Instead of:

const spy = spyOn(activatedRoute, 'params').and.returnValue(of({

try using this:

const spy = spyOnProperty(activatedRoute, 'params', 'get').and.returnValue(of({

spyOn -> spyOnProperty

Check the docs here.

Upvotes: 1

Related Questions