mardi 28 juin 2016

Angular2 Test HTTP Service Put - res.json() not a function

I am trying to unit test one the PUT functionality of one of my services with Karma + Jasmine. My GET test works just fine, but when I try to run the test for my PUT function I keep getting an error saying res.json() is not a function. What am I missing here? I followed the test setup as described here: http://ift.tt/1qdXGWS

Service snippet:

import { Injectable }     from '@angular/core';
import { Observable }     from 'rxjs/Observable';
import {FormularyDrug} from '../models/formularydrug';
import { Http, Response, RequestOptions, Headers, Request, RequestMethod} from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class FormularyDrugService {
    saveFormularyDrug(drug: FormularyDrug) : Observable<FormularyDrug>{
        let body = JSON.stringify({ drug });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ url: this.formularyDrugURL + drug.DrugId, headers: headers });
        return this.http.put(this.formularyDrugURL + drug.DrugId, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }
private extractData(res: Response) {
    let body = res.json();
    return body || [];
}
private handleError(error: any) {
    let errMsg = error.message || error.statusText || 'Server error';
    console.error(errMsg);
    return Observable.throw(errMsg);
}
}

Test class:

    import {describe, expect, it, xit, inject, injectAsync, beforeEachProviders} from '@angular/core/testing';
import {provide} from '@angular/core';
import {Headers, HTTP_PROVIDERS, BaseRequestOptions, XHRBackend, Response, ResponseOptions} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';

import {FormularyDrugService} from '../services/formularydrugs'
import {FormularyDrug} from '../models/formularydrug'

import 'rxjs/Rx'

describe('FormularyDrugService', () => {

  // All heed this block - it is required so that the test injector
  // is properly set up. Without doing this, you won't get the
  // fake backend injected into Http.

  // Also, you need to inject MockBackend as a provider before you wire
  // it to replace XHRBackend with the provide function!  So this is all
  // extremely important to set up right.
  beforeEachProviders(() => {
    return [
      HTTP_PROVIDERS,
      provide(XHRBackend, {useClass: MockBackend}),
      FormularyDrugService
    ];
  });

  //This test passes without issues
  it('should get list of formularyDrugs', inject([XHRBackend, FormularyDrugService], (mockBackend, drugService) => {
      mockBackend.connections.subscribe(
          (connection: MockConnection) => {
              connection.mockRespond(new Response(
                  new ResponseOptions({
                      body: [{ DrugId: 123 }]
                  }
                  )));
          });

      drugService.getFormularyDrugs().subscribe((drugs: FormularyDrug[]) => {
          expect(drugs.length).toBe(1);
          expect(drugs[0].DrugId).toBe(123);
      });
  }));

//This returns error -- res.json() is not a function
  it('should save existing formularyDrug', injectAsync([XHRBackend, FormularyDrugService], (mockBackend, drugService) => {
      return new Promise((resolve, reject) => {
          let data: FormularyDrug = new FormularyDrug("BrandName", "GenericName", "TAB", "2mg", "(2mL)", 1);

          mockBackend.connections.subscribe(connection => {
              connection.mockRespond(new ResponseOptions({ body: [{ DrugId: 1 }] }));
          });

          drugService.saveFormularyDrug(data).subscribe((drug: FormularyDrug) => {
              expect(drug).toBeDefined();
              expect(drug.DrugId).toBe(1);
              resolve();
          });
      });
  }), 300);

});

Error Message:

ERROR: 'res.json is not a function' Chrome 51.0.2704 (Windows 10 0.0.0): Executed 1 of 2 SUCCESS (0 secs / 0.024 secs) Chrome 51.0.2704 (Windows 10 0.0.0) FormularyDrugService should save existing formularyDrug FAILED Failed: Uncaught (in promise): res.json is not a function at ZoneDelegate.invoke (c:/Users/bharris/Source/Repos/Project/UI/node_modules/http://ift.tt/298v7Yq)

Aucun commentaire:

Enregistrer un commentaire