【问题标题】:How to test angular get request?如何测试角度获取请求?
【发布时间】:2018-10-30 13:52:19
【问题描述】:

我想测试获取请求相关的功能。 应触发请求并将值映射到相关对象。 相关代码为:

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 );
}

【问题讨论】:

  • 你能发布FetcherService 代码吗?也许fetchNews 是异步的并且断言是在设置fetchNewsResponse 之前完成的?
  • @JuniorDussouillez 我添加了一个编辑

标签: angular angular6


【解决方案1】:

您的问题有两个方面。首先,您正在尝试读取尚未从服务器(异步)返回的数据。但更重要的是,您正在尝试在单元(或功能)测试环境中进行端到端测试。 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.
    }));
});

【讨论】:

  • 谢谢你的回答,我已经接受了另一个,但是也赞成这个。
【解决方案2】:

我认为这与 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); }
);
}

【讨论】:

  • 感谢您的回答,至少部分问题与 Karma 的测试在与应用程序不同的端口上运行这一事实有关 - 并且服务器没有相关设置来处理此问题。我还添加了await delay(2000);相关代码进行测试,问题得到解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 2015-05-21
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
相关资源
最近更新 更多