我正在订阅角度定位服务在我的组件中:
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
到位置服务中的可用功能列表。
重要的是要告诉调用订阅时返回什么,
这是什么Location.subscribe.and.callFake(()=> Observable.of(Your stubbed data to return here));
is for.
我尝试创建一个小型演示:
这是它的链接,您可以尝试 fork 并根据需要修改它。
https://stackblitz.com/edit/angular-testing-c25ezq?file=app/app.component.spec.ts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)