Angular2

时间:2016-12-05 15:22:55

标签: unit-testing angular

我有一个DataService,我想声明正确地在查询字符串中设置了年份。有没有办法窥探http.get调用或访问它?我不知道测试这个的正确方法。我正在使用Angular 2.2.0。

DataService

    constructor(private http: Http) { }
    public getEnergyData(option: string): Promise<EnergyDataDto[]> {
        return this.http.get(this.getEnergyDataApiUrl(option)).toPromise().then((response) => {
            this.energyDataCache = this.parseEnergyDataResponse(response);
            return this.energyDataCache;
        }).catch(this.handleError);
    }

    protected getEnergyDataApiUrl(option: string) {
        return `/api/solar?year=${option}`;
    }

    protected parseEnergyDataResponse(response: Response) {
        return response.json().data;
    }

dataservice.spec.ts

describe('Given the DataService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [DataService, { provide: XHRBackend, useClass: MockBackend }],
    });
  });
  describe('When getting the energy data', () => {
    let backend: MockBackend;
    let service: EnergyDataService;
    let fakeEnergyData: EnergyDataDto[];
    let response: Response;

    const makeEnergyData = () => {
      let data = [];
      let one = new EnergyDataDto();
      one.year = 2007;
      one.countryName = 'Denmark';
      one.quantity = '100000';
      data.push(one);
      return data;
    };
    beforeEach(inject([Http, XHRBackend], (http: Http, be: MockBackend) => {
      backend = be;
      service = new EnergyDataService(http);
      fakeEnergyData = makeEnergyData();
      let options = new ResponseOptions({ status: 200, body: { data: fakeEnergyData } });
      response = new Response(options);
    }));
    it('should return fake values', async(inject([], () => {
      backend.connections.subscribe((c: MockConnection) => c.mockRespond(response));
      service.getEnergyData('all').then(data => {
        expect(data.length).toBe(1);
        expect(data[0].countryName).toBe('Denmark');
      });
    })));

    it('should use year in query string', async(inject([], () => {
      spyOn(service, 'getEnergyDataApiUrl').and.callThrough();
      backend.connections.subscribe((c: MockConnection) => c.mockRespond(response));
      service.getEnergyData('2007').then(data => {
        // I was hoping to use backendend somehow instead, but it's not in scope when I debug it.
        expect((<any>service).getEnergyDataApiUrl).toHaveBeenCalledWith('/api/solar?year=2007');
      });
    })));

0 个答案:

没有答案