我正在使用ActiveRoute从url读取一些值。
http://localhost:4200/project-test/#/add?orderId=156&customerNumber=431
我有单独的组件来读取ngOnInit()方法中的值。
摘录:
...
constructor(private activatedRoute: ActivatedRoute,
public sanitizer: DomSanitizer,
private customerAPIService : CustomerAPIService) {}
ngOnInit() {
this.orderId = this.activatedRoute.snapshot.queryParams["orderId"];
...
}
测试用例:
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();
...
});
});
我在编写测试时遇到错误
TypeError:undefined不是http://localhost:9876/_karma_webpack_/main.bundle.js中的'this.activatedRoute.snapshot.queryParams'对象(第350行)
答案 0 :(得分:4)
扩展@peeskillet回答。
有一个愚蠢的错误,比如我在模拟queryParamMap而不是snapshot.queryparams。
http://localhost:4200/project-test/#/add?order=156&customerNumber=431
以下是模拟activeroutes.snapshot.queryparams [“order”]的解决方案。
let orderId;
let customerNumber;
let mockActiveRoute;
...
beforeEach(() => {
...
mockActiveRoute = {
snapshot: {
queryParams: {
order: orderId,
customerNumber: customerNumber
}
}
};
});