我有一项根据天气数据提供数据的服务:
getCurrentWeatherData(location: Location, target?: string) {
return this.http.get<CurrentWeatherAPI>(
`${this.apiUrl}current?${
target === 'inputBtn' || target === 'enter'
? '&city=' + location.city
: '&lat=' + location.latitude + '&lon=' + location.longitude
}&key=${this.apiKey}&lang=pl`
);
}并对此进行测试:
describe('GetWeatherDataService', () => {
let httpController: HttpTestingController;
let service: GetWeatherData;
const location = {
city: 'name',
latitude: 67,
longitude: 10,
};
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [GetWeatherData, HttpClient],
}).compileComponents();
service = TestBed.inject(GetWeatherData);
httpController = TestBed.inject(HttpTestingController);
});
it('service should be created', () => {
expect(service).toBeTruthy();
});
it('#getCurrentWeatherData should use GET to retrieve data', () => {
service.getCurrentWeatherData(location, 'enter').subscribe();
const testRequest = httpController.expectOne(
'https://api.weatherbit.io/v2.0/current?&city=Name&key=1929292&lang=eu'
);
expect(testRequest.request.method).toEqual('GET');
});
});我的问题是,我想检查来自变量位置的城市名称是否等于从API获得的实际数据。我不知道如何使用测试模块从API中获取json。
发布于 2022-02-23 23:20:05
您不应该在unitTests中使用真正的API。而不是这个模拟的HttpClient。
https://angular.io/guide/testing-services#testing-http-services
https://stackoverflow.com/questions/71244681
复制相似问题