使用karma + jasmine测试订阅角度2中的位置(this.location.subscribe)

时间:2018-03-30 21:24:10

标签: angular karma-jasmine angular-test

我正在订阅我的组件中的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

如何创建一个存根或间谍,允许我传递位置的.subscribe功能。

Here is a similar question关于测试位置,但它指的是位置内的功能,而不是专门订阅位置。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

你必须这样做:

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));的用途。

我试图创建一个小型演示:

以下是指向它的链接,您可以尝试根据需要进行分叉和修改。

https://stackblitz.com/edit/angular-testing-c25ezq?file=app/app.component.spec.ts

相关问题