【发布时间】:2021-01-18 14:02:40
【问题描述】:
我对使用 Angular 的使用 HttpClientTestingModule 测试 http 服务的示例中的 testData 有误解。
我的问题是这个expect(data).toEqual(testData) 是假的可能性有多大。
当我们实际上没有向后端或某些 Stub 发送真正的请求时。
资源链接:https://angular.io/guide/http#expecting-and-answering-requests
it('can test HttpClient.get', () => {
const testData: Data = {name: 'Test Data'};
// Make an HTTP GET request
httpClient.get<Data>(testUrl)
.subscribe(data =>
// When observable resolves, result should match test data
expect(data).toEqual(testData)
);
// The following `expectOne()` will match the request's URL.
// If no requests or multiple requests matched that URL
// `expectOne()` would throw.
const req = httpTestingController.expectOne('/data');
// Assert that the request is a GET.
expect(req.request.method).toEqual('GET');
// Respond with mock data, causing Observable to resolve.
// Subscribe callback asserts that correct data was returned.
req.flush(testData);
// Finally, assert that there are no outstanding requests.
httpTestingController.verify();
});
【问题讨论】:
标签: angular unit-testing