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

标签 angular ionic2 angular2-testing

下面是我的服务类,它采用具有 json 格式数据的 url。

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

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

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

请忽略任何拼写错误。

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

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


});

注意:我必须根据我使用过的真实服务为这个服务创建一个模拟。我不确定这个模拟是否正确。请看看这个模拟。中提供的数据>get 这个模拟中的 url 位于另一个名为 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';
}

最佳答案

一个简单的方法是在 ServiceMock 中返回一个带有模拟数据的 Observable,而不使用 Http

数据模拟.ts

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

服务.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 返回的时间。

关于angular - 如何模拟包含 http 请求并返回 observable 的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45252158/

相关文章:

angular - 测试 Angular HttpInterceptor

ionic-framework - ionic2 删除蓝线颜色输入 md

material-design - 如何为 ionic 2 元素添加涟漪效应?

html - CSS 高级三按钮行格式化

angularjs - 由于在 RC6 中不推荐使用 addProvider,如何在 angular2 jasmine 测试规范中添加提供程序?

html - 如何设置继承自父ngb下拉菜单的宽度附加到主体?

angular - 为什么 (ngModel) 不工作?

angular - 打开 Clarity Signpost 不会发出其状态

angular - 需要使用 karma jasmine 解决组件的服务依赖错误

unit-testing - Angular 2 单元测试无法找到 debugElement