Angular 2 : jasmin test case for activateRoute.snapshot.queryParams[""]

Viewed 9030

I am reading some values from url by using ActiveRoute.

http://localhost:4200/project-test/#/add?orderId=156&customerNumber=431

I have separate component to read the values in ngOnInit() method.

snippet :

...

constructor(private activatedRoute: ActivatedRoute,
          public sanitizer: DomSanitizer,
          private customerAPIService : CustomerAPIService) {}

ngOnInit() {

   this.orderId = this.activatedRoute.snapshot.queryParams["orderId"];
   ...
}

Test case :

import { TestBed } from '@angular/core/testing';
import { CreateCustomer } from './create-customer.component';
import { ActivatedRoute } from '@angular/router';
import { CustomerAPIService } from "app/repackaging/service/customer.api.service";

describe('CreateCustomer', () => {
  let component;

  let mockActiveRoute;
  let mockCustomerAPIService;
  let mockQueryParamMap;

  beforeEach(() => {

     mockQueryParamMap = jasmine.createSpyObj('mockQueryParamMap', ['queryParams']);
     mockActiveRoute = {queryParamMap: mockQueryParamMap};

    TestBed.configureTestingModule({
        providers : [
           {
              provide: ActivatedRoute,
              useFactory: () => mockActiveRoute
           },
           {
              provide: CustomerAPIService,
              userFactory: () => mockCustomerAPIService
           }
      ],
      declarations :[
          CreateCustomer
      ]
    });

        component = TestBed.createComponent(CreateCustomer).componentInstance;
    });

    it('should run ngOninit function', function () {
       component.ngOnInit();

       ...

    });
});

I am getting below error while writing a test

TypeError: undefined is not an object (evaluating 'this.activatedRoute.snapshot.queryParams') in http://localhost:9876/_karma_webpack_/main.bundle.js (line 350)

1 Answers
Related