【发布时间】:2018-01-22 03:31:18
【问题描述】:
我正在使用 ActiveRoute 从 url 读取一些值。
http://localhost:4200/project-test/#/add?orderId=156&customerNumber=431
我有单独的组件来读取 ngOnInit() 方法中的值。
sn-p:
...
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 is not an object (evaluate 'this.activatedRoute.snapshot.queryParams') in http://localhost:9876/_karma_webpack_/main.bundle.js(第 350 行)
【问题讨论】:
-
this.activatedRoute.snapshot.queryParams当您的mockActivatedRoute没有snapshot属性时,您希望如何访问它。mockActivatedRoute被注入为ActivatedRoute -
@peeskillet 同意。我们需要为快照创建单独的间谍吗?如何添加用于模拟的快照?
-
为什么是
queryParamMap?你需要一个snapshot属性,而它又拥有自己的queryParams属性
标签: angular typescript jasmine