Currently, I am extracting values from the URL using ActiveRoute in my Angular project.
http://localhost:4200/project-test/#/add?orderId=156&customerNumber=431
In order to retrieve these values, I have implemented a separate component with an ngOnInit() method as shown below:
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 encountered an error while writing a test which states:
TypeError: undefined is not an object (evaluating 'this.activatedRoute.snapshot.queryParams') in http://localhost:9876/_karma_webpack_/main.bundle.js (line 350)