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

后端 未结 1 1546
梦毁少年i
梦毁少年i 2021-01-21 14:38

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

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


        
1条回答
  •  囚心锁ツ
    2021-01-21 14:57

    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

    0 讨论(0)
提交回复
热议问题