我正在尝试为ActivatedRoute
写一个简单的测试。这是我的测试结果。
it("should check if subscribes are called in init", () => {
const subRouteSpy = spyOn(activatedRouteStub.paramMap, "subscribe");
component.ngOnInit();
expect(subRouteSpy).toHaveBeenCalled();
});
我的TestBed config
:
const activatedRouteStub = {
paramMap: {
subscribe() {
return of();
}
}
};
TestBed.configureTestingModule({
declarations: [HomeFilterDrawerComponent],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub }
],
imports: [
FormsModule,
StoreModule.forRoot(appReducers),
HttpClientTestingModule,
RouterTestingModule
]
}).compileComponents();
测试不断给我Expected spy subscribe to have been called.
,但不确定我到底在做什么错。
组件ngOnInit
中的代码。
this.route.paramMap.subscribe(params => {
if (params["params"].slug !== undefined) {
}
});
答案 0 :(得分:2)
当您通过activatedRouteStub
提供对象时,Angular正在克隆您的useValue
对象。因此,您在监视原始的存根对象,但是您的组件看到的是一个克隆的对象,没有附加间谍。
始终从喷油器获取服务不要引用 提供给测试模块中的userServiceStub对象 测试的主体。这是行不通的!注入了userService实例 组件中的对象是完全不同的对象, 提供的userServiceStub。
要解决此问题,您需要使用TestBed.get
let activatedRoute;
const activatedRouteStub = {
paramMap: {
subscribe() {
return of();
}
}
};
TestBed.configureTestingModule({
declarations: [HomeFilterDrawerComponent],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub }
],
imports: [
FormsModule,
StoreModule.forRoot(appReducers),
HttpClientTestingModule,
RouterTestingModule
]
}).compileComponents();
beforeEach(() => {
fixture = TestBed.createComponent(NewsComponent);
component = fixture.componentInstance;
// Get a reference to the injected value
activatedRoute = TestBed.get(ActivatedRoute);
});
it("should check if subscribes are called in init", () => {
// Spy on the injected value
const subRouteSpy = spyOn(activatedRoute.paramMap, "subscribe");
component.ngOnInit();
expect(subRouteSpy).toHaveBeenCalled();
});
或者,您可以保持代码不变,但是将useValue
更改为useFactory
。这将允许您绕过克隆行为:
providers: [{ provide: ActivatedRoute, useFactory: () => activatedRouteStub }]
答案 1 :(得分:0)
像这样创建存根:
eval
像这样提供ParamMap:
const paramMap: ParamMap = {
keys: [],
has: name => true,
get: name => '10',
getAll: name => []
};