1

I have trying to get json data from when i calling service method. I got a return object but i didn't get json data. Which part i have to change?

"goods.services.ts"

getAllData(): Observable<Product>{

    let jwtTok1 ="Something";
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Token ' + jwtTok1);
    let options = new RequestOptions({ headers: headers, body: {} });
    return this.http.get(BASE_URL_GOODS, options)
      .map((res:Response) => {return Observable.of ({type: "success", payload:  res.json().data})})

      .catch(error => this.handleError(error));

}

Another is test case file "goods.component.spec.ts"

import {
    inject,
  TestBed,fakeAsync,tick
} from '@angular/core/testing';
import { Component } from '@angular/core';
import {
    BaseRequestOptions,
    ConnectionBackend,
    Http
} from '@angular/http';
import { MockBackend,MockConnection } from '@angular/http/testing';
// Load the implementations that should be tested
import { Observable } from 'rxjs/Rx';
import { AppState } from '../app.service';
import { ActionReducer, Action, Store } from '@ngrx/store';
import { AppStore } from '../models/appstore.model';
import {goodsDescriptionComponent } from './goods-desc.component';
import { goodsService } from '../common/service/goods.service';
import { goodsReducer } from '../common/reducers/goods.reducer';
import {provideStore} from '@ngrx/store';
import { goods} from '../common/models/goods.model';
import { Input } from '@angular/core';

describe('GoodsDescriptionComponent', () => {
  //let store:Store<AppStore>;
  beforeEach(() => TestBed.configureTestingModule({
    providers: [
      BaseRequestOptions,
      MockBackend,
      {
        provide: Http,
        useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) {
          return new Http(backend, defaultOptions);
        },
        deps: [MockBackend, BaseRequestOptions]
      },
      goodsService, provideStore({goodsData: goodsReducer}),goodsDescriptionComponent
    ]}));
it('should url will be same  ', 
    inject(
      [goodsService, MockBackend],
      fakeAsync((service:ProductsService, backend: MockBackend) => {
        backend.connections.subscribe((connection: MockConnection) => {


          expect(connection.request.url).toBe(
            'http://localhost:3001/goodsMS/');

        });
        service.getAllData();

        console.log("goods what we got: ",service.getAllData());
      })));
});

Getting Response Result is,

enter image description here

This Response object getting from console in google chrome. Still i can't get correct solution for getting json data from service method call.i can't reach json server. my json server URL is , "http://localhost:3001/goods". please anyone help me. Thanks in advance.

Sithu05
  • 146
  • 5
  • 12
  • You said `I got a return object but i didn't get json data`, where did it happen in your code? – Michael Nov 11 '16 at 11:28
  • In "goods.component.spec.ts" file, i got a response in "console.log("goods what we got: ",service.getAllData());" The response like, please the above image. @Michael – Sithu05 Nov 11 '16 at 13:58
  • Can any one help me.? still, i am struck on this part. the main thing is, can not reach json server. – Sithu05 Nov 15 '16 at 07:29

1 Answers1

1
  1. You need to set a response on the connection

    backend.connections.subscribe((connection: MockConnection) => {
      expect(connection.request.url).toBe(
        'http://localhost:3001/goodsMS/');
    
      connection.mockRepond(new Response(new ResponseOptions({
        body: `{"some":"json", "response":"body"}`
      }));
    });
    
  2. You need to subscribe to your service call

    service.getAllData().subscribe((result) => {
      expect(somethingWithData)
    })
    tick()
    

    since you are using fakeAsync, you need to tick to force completion of the asynchronous observable. If you use async instead of fakeAsync, then you don't need to call tick

  3. You should not be returning an Observable in the service method map function. Just return a normal object.

    .map((res:Response) => {type: "success", payload:  res.json().data})
    
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Thanks @peeskillet. But This is not a correct solution for this issue. because i need to validate dynamic 'JsonData" from api call. Your answer willbe used for to validating static jsonData. My problem is i can't get json data from service method(api call). – Sithu05 Nov 11 '16 at 14:04
  • Can any one help me.? still, i am struck on this part. the main thing is, can not reach json server. – Sithu05 Nov 15 '16 at 07:30