在对 Angular 的 HttpClient.get(...) 函数进行单元测试时,似乎 TypeScript 在使用给定的 responseType 监视 HttpClient.get(...) 时无法正确检查类型。
升级到 Angular 11 后出现此错误。
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [AppComponent],
}).compileComponents();
});
it('should check HttpClient.get()', () => {
const http = TestBed.inject(HttpClient);
const httpGetSpy = spyOn(http, 'get').and.returnValue(of('Test result.'));
http.get('/test/url', { responseType: 'text' });
expect(httpGetSpy).toHaveBeenCalledWith(
'/test/url',
{ responseType: 'text'}
// ^^^ Error:
// "Type '"text"' is not assignable to type '"json" | undefined'.
);
});
除了上面的简单复制器之外,这是一个更合理的示例,因为它出现在我的生产代码中:
// example.service.ts
@Injectable({ providedIn: 'root' })
export class ExampleService {
constructor(private http: HttpClient) { }
doSomething(): Observable<any> {
return this.http.get('/some/url', { responseType: 'text' });
}
}
// example.service.spec.ts
describe('ExampleService', () => {
let service: ExampleService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
service = TestBed.inject(ExampleService);
});
it('should be created', () => {
const http = TestBed.inject(HttpClient);
const httpGetSpy = spyOn(http, 'get').and.returnValue(of('Test result.'));
service.doSomething().subscribe();
expect(httpGetSpy).toHaveBeenCalledWith('/some/url', { responseType: 'text' });
});
});