import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { DataSourceValue } from '../models/data-source-value';
import { SelectBoxDataSourceService } from './select-box-data-source.service';

describe('SelectBoxDataSourceService', () => {
  let httpClient: HttpTestingController;
  let selectBoxDataSourceService: SelectBoxDataSourceService;
  const testUrl = 'testUrl';

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

    httpClient = TestBed.inject(HttpTestingController);
    selectBoxDataSourceService = TestBed.inject(SelectBoxDataSourceService);
  });

  it('should be created', () => {
    const service: SelectBoxDataSourceService = TestBed.inject(SelectBoxDataSourceService);
    expect(service).toBeTruthy();
  });

  it('should return some data source values', () => {
    const expectedDataSourceValues: DataSourceValue = {
      id: 'test1',
      label: 'test2',
      value: 'test3',
    };

    selectBoxDataSourceService.getDataSourceValues(testUrl).subscribe(
      (dataSourceValues) => expect(dataSourceValues).toEqual(expectedDataSourceValues),
      () => fail()
    );

    httpClient.expectOne(testUrl).flush(expectedDataSourceValues);
    httpClient.verify();
  });

  it('should return an error when the given url returns a 404', () => {
    selectBoxDataSourceService.getDataSourceValues(testUrl).subscribe(
      () => fail(),
      (dataSourceValues) => expect(dataSourceValues).toBeTruthy()
    );

    const errorEvent = new ErrorEvent('not found');
    httpClient.expectOne(testUrl).error(errorEvent, {
      status: 404,
      statusText: 'OK',
    });
    httpClient.verify();
  });
});
