如何模拟包含http请求的服务并返回一个observable?

时间:2017-07-22 07:58:27

标签: angular ionic2 angular2-testing

下面是我的Service类,它带有一个带有json格式数据的url。

service.ts

i

以下是我的page1.ts文件,它使用该服务并从服务中获取数据。

page1.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');
    }
}

请忽略任何错字。

下面是我在这个页面的spec文件,我想测试这个异步http get方法

page1.spec.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);
          });
} 

注意:我必须根据我使用的真实服务为此服务创建一个模拟。我不确定这个模拟是否正确。请看看这个模拟。{{{{{{ 1}}此模拟中的url位于另一个名为 data.mock.ts 的文件夹中。

service.mock.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.
  })


});

data.mock.ts

get

1 个答案:

答案 0 :(得分:0)

执行此操作的一种简单方法是使用ServiceMock中的模拟数据返回Observable,而不使用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);
  }
}

然后你可以像这样测试它。

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);
}));

您必须使用fakeAsync,因为该函数订阅了异步运算符。 tick()模拟来自observable的数据返回的时间。