代码之家  ›  专栏  ›  技术社区  ›  Jackson Vaughan

测试用karma+jasmine订阅angular 2中的位置(此位置。订阅)

  •  2
  • Jackson Vaughan  · 技术社区  · 7 年前

    我正在订阅 angular Location service 在我的组件中:

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

    我希望能够将其与我的其他组件一起测试。

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

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

    我正在将其作为提供者配置到我的测试床中:

    {provide: Location, useValue: locationStub }
    

    当我跑步时 ng test ,我收到此错误 this.location.subscribe is not a function .

    如何创建允许我通过的存根或间谍。订阅位置功能。

    Here is a similar question 在测试位置上,但它是指位置中的函数,而不是专门订阅位置。

    非常感谢您的帮助。

    1 回复  |  直到 7 年前
        1
  •  3
  •   HDJEMAI    6 年前

    你必须这样做:

    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 位置服务中可用功能的列表。

    打电话给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