使用业力+茉莉花测试订阅角度2中的位置(this.location.subscribe) [英] Test subscribing to Location in angular 2 with karma+jasmine (this.location.subscribe)

查看:75
本文介绍了使用业力+茉莉花测试订阅角度2中的位置(this.location.subscribe)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在组件中订阅角度位置服务,例如:

I am subscribing to the angular Location service in my component as such:

this.location.subscribe((ev:PopStateEvent) => {
    this.lastPoppedUrl = ev.url;
});

我希望能够与其余组件一起对其进行测试.

I'd like to be able to test it along with the rest of my component.

现在我的component.spec.ts文件中有这个存根

Right now I have this stub in my component.spec.ts file

let locationStub: Partial<Location>;
    locationStub = {
}

我正在将其配置为提供程序到我的TestBed中:

And I am configuring it into my TestBed as a provider:

{provide: Location, useValue: locationStub }

当我运行ng test时,出现此错误this.location.subscribe is not a function.

When I run ng test, I get this error this.location.subscribe is not a function.

如何创建存根或间谍,使我能够传递Location的.subscribe功能.

How can I create a stub or spy that will allow me to pass the .subscribe functionality of Location.

这是关于测试的类似问题位置,但它是指位置中的功能,而不是专门订阅位置.

Here is a similar question on testing Location, but it is referring to functions within Location, not specifically subscribing to 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添加到位置服务中可用功能的列表中.

So you have to add subscribe to the list of the available functions in the Location service.

并且重要的是在调用订阅时告诉返回什么,然后

And it's important to tell what to return then when calling the subscribe,

这是Location.subscribe.and.callFake(()=> Observable.of(Your stubbed data to return here));的作用.

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

I've tried to create a small demo:

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

Here is the link to it, you can try to fork and modify it as needed.

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

这篇关于使用业力+茉莉花测试订阅角度2中的位置(this.location.subscribe)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆