如何测试角度获取请求?

时间:2018-10-30 13:52:20

标签: angular angular6

我想测试与请求相关的功能。 应该触发请求,并将值映射到相关对象。 相关代码是:

it('Should have values set', () => {
  const service: FetcherService = TestBed.get(FetcherService);
  const technologyString = 'technology';
  service.fetchNews(technologyString);
  expect(service.fetchNewsResponse.category === technologyString);
});

但是当前可能不相关,因为相关测试因Karma而失败,并且消息为

TypeError: Cannot read property 'category' of undefined

我应该更改哪些代码来解决此问题?

编辑:

与service.fetchNews相关的代码为:

public fetchNews(category: string) {
this.httpClient.get<News>('http://localhost:8080/news/' + this.country + '/' + category + '/')
.subscribe(data => this.fetchNewsResponse = data );
}

2 个答案:

答案 0 :(得分:2)

您的问题有两个方面。首先,您尝试从服务器读取尚未(异步)返回的数据。但更重要的是,您正在尝试在单元(或功能)测试环境中进行端到端测试。 Difference between functional test and end-to-end test

对于单元测试使用httpClient进行http调用的服务,使用HttpClientTestingModule和HttpTestingController可为您提供最大的灵活性。请参阅此处的文档:https://angular.io/guide/http#testing-http-requests

对于您而言,最终结果应如下所示:

describe('FetchNews Service', () => {
    let httpMock: HttpTestingController;
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ HttpClientTestingModule ],
            providers: [ FetcherService ]
        });
        httpMock = TestBed.get(HttpTestingController);
    });
    it('should have values set', async(() => {
        const service: FetcherService = TestBed.get(FetcherService);
        const technologyString = 'technology';
        const responseData = {category: technologyString};
        const country = 'italy';
        service.fetchNews(technologyString);
        let req = httpMock.expectOne('http://localhost:8080/news/' + country + '/technology/');
        expect(req.request.method).toEqual('GET');
        req.flush(responseData); // send responseData as result of the get
        expect(service.fetchNewsResponse.category).toEqual(technologyString); // may need to be tested after observable resolves.
    }));
});

答案 1 :(得分:1)

我认为这与API的响应有关。通过在GET请求中定义错误处理程序来测试是否收到任何错误,例如:

public fetchNews(category: string) {
this.httpClient.get<News>('http://localhost:8080/news/' + this.country + '/' + category 
+ '/')
.subscribe(data => {
this.fetchNewsResponse = data
},
 error => { console.log('Error:', error); }
);
}