这通常是由于测试代码与被测试的代码之间存在异步问题所导致的。我们可以在测试代码中使用fakeAsync和tick()函数来解决此问题。以下是一个示例:
// HTTP拦截器
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(request: HttpRequest
return next.handle(request);
} }
// 单元测试 describe('MyInterceptor', () => { let httpMock: HttpTestingController; let httpClient: HttpClient;
beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true } ] });
httpMock = TestBed.inject(HttpTestingController);
httpClient = TestBed.inject(HttpClient);
});
afterEach(() => { httpMock.verify(); });
it('should add X-Requested-With header', fakeAsync(() => { const url = 'https://example.com'; httpClient.get(url).subscribe();
const httpRequest = httpMock.expectOne(url);
expect(httpRequest.request.headers.get('X-Requested-With')).toBe('XMLHttpRequest');
httpRequest.flush({});
tick();
})); });
在上面的代码中,我们使用了fakeAsync()函数来避免异步问题。接下来,我们通过httpClient.get()方法来执行HTTP请求。然后,我们调用httpMock.expectOne()方法来断言我们的拦截器是否已经正确地添加了'X-Requested-With'头部。最后,我们使用httpRequest.flush()方法来模拟HTTP响应,并使用tick()方法来等待异步操作完成。
通过这种方式,我们可以在Angular 12中正确地测试HTTP拦截器中的expectOne()方法。