首页 > 解决方案 > 从 http 请求角度订阅时出错

问题描述

我正在开发测试驱动的角度应用程序。(不要问为什么,这就是客户想要的)

以下是我不能modifyedit.

  it('should get results', fakeAsync(
    inject(
      [XHRBackend, NewsService ],
      (mockBackend: MockBackend, newsService: NewsService) => {

      const expectedUrl = 'https://api.nytimes.com/svc/topstories/v2/home.json?api-key=315a5a51483b469a918246dc2753b339';

      mockBackend.connections.subscribe((connection : MockConnection) => {
          expect(connection.request.method).toBe(RequestMethod.Get);
          expect(connection.request.url).toBe(expectedUrl);

          connection.mockRespond(new Response(
            new ResponseOptions({ body: mockResponse })
          ));
        });

      newsService.getSectionNews('home')
        .subscribe( (res: any) => {
            expect(res).toEqual(mockResponse);
        });
    })
  ));

所以根据规范,我需要编写我的前端代码。

所以这是我写的,

  import { Http } from '@angular/http';

  constructor(private http: Http) {}

  getSectionNews(sectionName: string): any {
    // fetch news of that sectionName
   // return this.mockResponse;
   const expectedUrl = 'https://api.nytimes.com/svc/topstories/v2/home.json?api-key=315a5a51483b469a918246dc2753b339';
   return this.http.get(expectedUrl).subscribe(res => res);
  }

但是在运行测试用例时,我收到了这个错误:

TypeError: newsService.getSectionNews(...).subscribe 不是函数

请告诉我我在这里做错了什么。

我想通过测试用例。

更新

更新我的服务规范后。

  getSectionNews(sectionName: string): Observable<any> {
    const expectedUrl = `https://api.nytimes.com/svc/topstories/v2/${sectionName}.json?api-key=315a5a51483b469a918246dc2753b339`;
    return this.http.get(expectedUrl);
  }

现在我收到以下错误,

预期的状态响应:null 用于 URL 的 null:null 等于 Objectt({ status: 'OK', copyright: 'C ...

标签: javascriptangulartypescriptjasminesubscribe

解决方案


推荐阅读