此问题的解决方法是更新HttpClientTestingModule。 在spec文件中,在导入HttpClientTestingModule时,需要添加HttpClientInMemoryWebApiModule导入,并使用createTestBed创建测试环境。
import { TestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api'; import { InMemoryDataService } from './in-memory-data.service'; import { DataService } from './data.service';
describe('DataService', () => { let httpTestingController: HttpTestingController; let service: DataService;
beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule, HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService) ] });
httpTestingController = TestBed.inject(HttpTestingController);
service = TestBed.inject(DataService);
});
afterEach(() => { httpTestingController.verify(); });
it('should retrieve data', () => { const expectedData = {name: 'test'};
service.getData().subscribe(data => {
expect(data).toEqual(expectedData);
});
const req = httpTestingController.expectOne('api/data');
expect(req.request.method).toEqual('GET');
req.flush(expectedData);
}); });