测试订阅 Location in angular 2 with karma+jasmine (this.location.subscribe)
Test subscribing to Location in angular 2 with karma+jasmine (this.location.subscribe)
我在我的组件中订阅了 angular Location service:
this.location.subscribe((ev:PopStateEvent) => {
this.lastPoppedUrl = ev.url;
});
我希望能够将它与我的其他组件一起进行测试。
现在我的 component.spec.ts 文件中有这个存根
let locationStub: Partial<Location>;
locationStub = {
}
我正在将它作为提供者配置到我的 TestBed 中:
{provide: Location, useValue: locationStub }
当我 运行 ng test
时,我得到这个错误 this.location.subscribe is not a function
。
如何创建允许我传递 Location 的 .subscribe 功能的存根或间谍。
测试 Location,但它指的是 Location 中的函数,而不是专门订阅 Location。
非常感谢任何帮助。
你必须这样做:
beforeEach(() => {
// Mock the location here instead, then pass to the NavBarComponent
loc = jasmine.createSpyObj("Location", ["back", "subscribe"]);
Location.subscribe.and.callFake(()=> Observable.of(your stubbed data to return here));
testNavBarComponent = new NavBarComponent(loc);
});
因此您必须将 subscribe
添加到定位服务中的可用功能列表中。
重要的是要告诉 return 什么,然后在调用订阅时,
这就是 Location.subscribe.and.callFake(()=> Observable.of(Your stubbed data to return here));
的用途。
我尝试创建一个小演示:
这里是link,你可以根据需要尝试fork和修改它。
https://stackblitz.com/edit/angular-testing-c25ezq?file=app/app.component.spec.ts
我在我的组件中订阅了 angular Location service:
this.location.subscribe((ev:PopStateEvent) => {
this.lastPoppedUrl = ev.url;
});
我希望能够将它与我的其他组件一起进行测试。
现在我的 component.spec.ts 文件中有这个存根
let locationStub: Partial<Location>;
locationStub = {
}
我正在将它作为提供者配置到我的 TestBed 中:
{provide: Location, useValue: locationStub }
当我 运行 ng test
时,我得到这个错误 this.location.subscribe is not a function
。
如何创建允许我传递 Location 的 .subscribe 功能的存根或间谍。
非常感谢任何帮助。
你必须这样做:
beforeEach(() => {
// Mock the location here instead, then pass to the NavBarComponent
loc = jasmine.createSpyObj("Location", ["back", "subscribe"]);
Location.subscribe.and.callFake(()=> Observable.of(your stubbed data to return here));
testNavBarComponent = new NavBarComponent(loc);
});
因此您必须将 subscribe
添加到定位服务中的可用功能列表中。
重要的是要告诉 return 什么,然后在调用订阅时,
这就是 Location.subscribe.and.callFake(()=> Observable.of(Your stubbed data to return here));
的用途。
我尝试创建一个小演示:
这里是link,你可以根据需要尝试fork和修改它。
https://stackblitz.com/edit/angular-testing-c25ezq?file=app/app.component.spec.ts