I have a service which provide data from the weather data:
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`
);
}
And tests for that:
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');
});
});
My problem is that I want to check that the name of the city from the variable location is equal to real data getting from the API. I don't know how to get json from the API using testing module.
CodePudding user response:
You shouldn't use real API in unitTests. Instead of this mock HttpClient.
https://angular.io/guide/testing-services#testing-http-services
CodePudding user response:
I wrote something like this: /but when I change the name of the city, test is still green/
it('it should return expected current weather data', (done: DoneFn) => {
const expectedData: CurrentWeatherAPI = {
data: [
{
city_name: 'London',
},
],
count: 1,
};
httpClientSpy.get.and.returnValue(of(expectedData));
service.getCurrentWeatherData(location, 'btn').subscribe({
next: (data) => {
expect(data.data[0].city_name)
.withContext('expected data')
.toEqual(expectedData.data[0].city_name);
done();
},
error: done.fail,
});
});