Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.6 kB
3
Indexable
Never
describe('MyService', () => {
  let service: MyService;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [MyService],
    });

    service = TestBed.inject(MyService);
    httpTestingController = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  describe('getLocationFromAddress$', () => {
    it('should return an observable', () => {
      const observable = service.getLocationFromAddress$('postcode');
      expect(observable).toBeInstanceOf(Observable);
    });

    it('should emit a value of type AALocation', done => {
      const expectedLocation = { latitude: 51.5074, longitude: -0.1278 };
      service.getLocationFromAddress$('postcode').subscribe({
        next: location => {
          expect(location).toEqual(expectedLocation);
          done();
        },
        error: done.fail,
      });

      const req = httpTestingController.expectOne(
        'https://maps.googleapis.com/maps/api/geocode/json?address=postcode&componentRestrictions%5Bcountry%5D=UK'
      );
      req.flush({
        results: [
          {
            formatted_address: 'London, UK',
            geometry: {
              location: { lat: expectedLocation.latitude, lng: expectedLocation.longitude },
            },
          },
        ],
        status: 'OK',
      });
    });

    it('should complete without errors', done => {
      service.getLocationFromAddress$('postcode').subscribe({
        complete: done,
        error: done.fail,
      });

      const req = httpTestingController.expectOne(
        'https://maps.googleapis.com/maps/api/geocode/json?address=postcode&componentRestrictions%5Bcountry%5D=UK'
      );
      req.flush({ status: 'OK' });
    });
  });

  describe('getLocationFromAddress', () => {
    it('should return a promise that resolves to AALocation', async () => {
      const expectedLocation = { latitude: 51.5074, longitude: -0.1278 };
      const promise = service.getLocationFromAddress('postcode');
      const req = httpTestingController.expectOne(
        'https://maps.googleapis.com/maps/api/geocode/json?address=postcode&componentRestrictions%5Bcountry%5D=UK'
      );
      req.flush({
        results: [
          {
            formatted_address: 'London, UK',
            geometry: {
              location: { lat: expectedLocation.latitude, lng: expectedLocation.longitude },
            },
          },
        ],
        status: 'OK',
      });
      const location = await promise;