2

Below is my Service class which is taking a url which has a json format data.

service.ts

    import { Injectable } from "@angular/core";
    import {  Http } from '@angular/http';
    import { Observable } from "rxjs/Observable";

    @Injectable()

    export class Service {

    public http: string;
    constructor(private http: Http) { }

    getGoogle():Observable<any> {
        console.log("Inside service");


      return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
    }
}

Below is my page1.ts file which uses the service and gets the data from the service.

page1.ts

import { Component } from '@angular/core';
import { Service } from "../../services/service";


@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html',
})
export class Page1 {

  constructor(private service: Service) {

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad Page1');
  }

  get() {
    console.log("inside get method");
    this.service.getGoogle().subscribe(
      (response:Response)=>{
       console.log('The resonse is', response);
          });
} 

Please ignore any typo.

Below is my spec file for this page, where I want to test this asynchronous http get method

page1.spec.ts

import { TestBed, async, ComponentFixture, inject } from '@angular/core/testing';
import { Page1 } from './page1';
import { IonicModule, NavController } from "ionic-angular";
import { DebugElement } from "@angular/core";
import { Service } from "../../services/service";
import { By } from "@angular/platform-browser";


describe('Page1 to be tested', () => {

    let fixture: ComponentFixture<Page1>;
    let comp: Page1;
    let de: DebugElement;
    let el: HTMLElement;



    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [Page1],
            imports: [
                IonicModule.forRoot(Page1),

            ],
            providers: [NavController,
         //need to provide service I have already imported it.

            ],
        }).compileComponents();

    }

    ));
    beforeEach(() => {
        fixture = TestBed.createComponent(Page1);
        comp = fixture.componentInstance;
        de = fixture.debugElement; 

    });

    afterEach(()=>{
        fixture.destroy();
    })

    it('is created', () => {
        expect(comp).toBeTruthy();
        expect(fixture).toBeDefined();
    });

    it('Testing the service', ()=>{
        //testing service.
  })


});

Note: I have to create a mock for this service, based on the real service that I have used.I am not sure whether this mock is correct.Please have a look at this mock.The data provided in the get url in this mock is in another folder which is named as data.mock.ts.

service.mock.ts

import { Observable } from 'rxjs/Observable';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

export class ServiceMock {
    public http: Http;
    url: string;
    getGoogle(): Observable<any> {
        return this.http.get('./data.mock').map((res) => {
            res.json();
        });
    }
}

data.mock.ts

export class Data {
    name: string = 'Aditya';
    profession: string = 'Developer';
}
user8348978
  • 81
  • 1
  • 1
  • 7
  • I just answered a similar question: https://stackoverflow.com/questions/45253631/how-do-i-mock-the-json-response-for-testing-in-angular-4-project/45255340#45255340 Good luck – Eden Jul 22 '17 at 13:57

1 Answers1

0

A simple way to do this would be to return an Observable with your mocked data in ServiceMock without using Http.

data.mock.ts

export class Data {
  public static data = {
    name: string = 'Aditya',
    profession: string = 'Developer'
  };
}

service.mock.ts

import { Data } from './data.mock';
import 'rxjs/Rx'; 

export class ServiceMock {

  getGoogle(): Observable<any> {
    return Observable.of(Data.data);
  }
}

And then you can test it like this.

it('tests that it gets something and prints the response', fakeAsync(() => {
  spyOn(comb.service, 'getGoogle');
  spyOn(console, 'log');
  comb.get();
  tick();
  expect(comb.service.getGoogle).toHaveBeenCalled();
  expect(console.log).toHaveBeenCalledWith('The resonse is', Data.data);
}));

You have to to use fakeAsync because the function subscribes to an async operator. tick() simulates the time for the data from the observable to return.

emroussel
  • 1,077
  • 11
  • 19