在Angular 7中,你可以使用HttpClientTestingModule
来测试HTTP请求。以下是一个示例,展示了如何在单元测试中捕获HttpErrorResponse
:
import { TestBed, async } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
describe('YourComponent', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [ YourService ] // 如果你正在测试一个服务
}).compileComponents();
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
}));
// 其他测试代码...
});
it('should handle HttpErrorResponse', () => {
const mockErrorResponse = { status: 400, statusText: 'Bad Request' };
const data = 'Invalid request parameters';
httpClient.get('/api/your-endpoint').subscribe(
() => fail('should have failed with the HttpErrorResponse'),
(error: HttpErrorResponse) => {
expect(error.status).toEqual(400);
expect(error.error).toEqual(data);
}
);
const req = httpTestingController.expectOne('/api/your-endpoint');
req.flush(data, mockErrorResponse);
});
在这个例子中,我们模拟了一个返回400错误的HTTP请求。在subscribe
方法中,我们使用HttpErrorResponse
来捕获错误,并断言它的状态码和错误消息。
请注意,我们使用httpTestingController.expectOne
来捕获我们模拟的HTTP请求,并使用req.flush
来返回模拟的响应。
这是一个简单的示例,演示了如何在单元测试中捕获HttpErrorResponse
。你可以根据你的需求进行调整和扩展。