Test subscribing to Location in angular 2 with karma+jasmine (this.location.subscribe)

萝らか妹 提交于 2019-12-02 04:03:45

问题


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.

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

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

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

{provide: Location, useValue: locationStub }

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

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.

Any help is much appreciated.


回答1:


You have to do it like this:

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);
});

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,

This is what Location.subscribe.and.callFake(()=> Observable.of(Your stubbed data to return here)); is for.

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



来源:https://stackoverflow.com/questions/49581616/test-subscribing-to-location-in-angular-2-with-karmajasmine-this-location-subs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!