首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试角2中的API调用

测试角2中的API调用
EN

Stack Overflow用户
提问于 2017-07-29 22:25:20
回答 1查看 2.2K关注 0票数 4

我有以下两个组件和一个由双方共享的服务。我需要对它们进行单元测试,但是我无法知道如何测试服务对以下组件的依赖性。

代码语言:javascript
复制
//a.component.ts
import { Component, Input } from '@angular/core';
import { Http, Response } from '@angular/http';
import { SharedService } from './shared/shared.service';

@Component({
  selector: 'a',
  providers: [],
  templateUrl: './a.component.html'
})
export class AComponent {
  ax = {};

  constructor(public helperService: SharedService) {
    helperService.getFromAPI().subscribe(data => this.ax = data["people"]);
  }

}



//b.component.ts
import { Component } from '@angular/core';
import { SharedService } from './shared/shared.service';
import { Subscription }   from 'rxjs/Subscription';


@Component({
  selector: 'b',
  providers: [],
  templateUrl: './b.component.html'
})

export class BComponent {
  subscription: Subscription;
  x = '';

  constructor(public helperService: SharedService) {}

  ngOnInit() {
    this.subscription = this.helperService.c$.subscribe(
      data => {
        this.x = data;
      });
  }
}

这是调用API的服务。另一个函数setC在单击按钮时将值添加到可观察到的值,该值将由BComponent访问。

代码语言:javascript
复制
// shared.service
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';

@Injectable()
export class SharedService {

  private c = new Subject<string>();
  c$ = this.c.asObservable();

  constructor(
    private http: Http
  ) { }

  getFromAPI() {
    return this.http.get('url')
      .map((res: Response) => res.json());
  }

  setC(data: string) {
    this.c.next(data);
  }
}

我怎么才能在茉莉花里测试这个?到目前为止,我的努力是徒劳的。

我试过这样做

代码语言:javascript
复制
it('xxx', inject([SharedService], (service: SharedService) => {
    const fixture = TestBed.createComponent(AComponent);
    const app = fixture.componentInstance;

    spyOn(service, 'c$').and.callThrough;

    service.setC('Random Name');
    expect(service.c$).toHaveBeenCalled();

  }));

这不能通过Expected spy c$ to have been called.进行测试。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-29 22:33:33

你似乎在监视一个Observable,但当你调用setC时,所称的是你的主体的next函数。所以你可能会想监视这个。

spyOn(service.c, 'next').and.callThrough()这样的东西应该能起作用。

希望能帮上忙。

更新:如果您想要明确地测试您的Observable的功能,那么我只需订阅它,调用setC并测试响应,如下所示:

代码语言:javascript
复制
service.$c.subscribe((data) => {
    expect(data).toBe('foobar');
});
service.setC('foobar');

要在评论中回答您的问题:由于您的c是私有的,您可以像这样监视它:spyOn(service['c'], 'next').and.callThrough()。您的ide可能会唠叨着监视私有方法,在本例中,您可以添加如下的any类型:spyOn<any>(...)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45394625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档