我该如何测试这个Angular 2服务?

时间:2016-07-20 14:16:13

标签: testing typescript angular

我的Angular应用程序中有以下服务:

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

@Injectable()
export class BookService {

  constructor(private http: Http) {}

  getList() {
    return this.http.get('/api/books.json');
  }
}

我如何测试getList()功能?

我不需要每一个细节,只需要一些大方向。我认为这是非常陈旧的领域,但我很难找到关于人们通常如何测试此类内容的文档。一旦我知道了要走的路,我可能会自己追逐细节。

2 个答案:

答案 0 :(得分:3)

import {addProviders, inject} from '@angular/core/testing';

describe('my code', () => {
  beforeEach(() => {
    addProviders([
      BookService, 
      HTTP_PROVIDERS,
      MockBackend,
      {provide: XHRBackend, useExiting: MockBackend}]);
  });

  it('does stuff', inject([BookService], (service) => {
    // actual test
  });
});

有关详细信息,请参阅https://angular.io/docs/ts/latest/api/http/testing/MockBackend-class.html

答案 1 :(得分:1)

我自己也搞砸了一些。以下是我为测试本身提出的建议:

  it('should assign a list of books', inject([BookService, MockBackend, Http], (bookService, backend, http) => {
    backend.connections.subscribe(connection => {
      var mockResponse = new Response(new ResponseOptions({
        body: [{ name: 'Whiteboard Interviews' }]
      }));
      connection.mockRespond(mockResponse);
    });

    let service = new BookService(http);
    service.getList().subscribe(response => {
      expect(response.json()).toEqual([{ name: 'Whiteboard Interviews' }]);
    });
  }));

这是完整的spec文件:

/* tslint:disable:no-unused-variable */

import { provide } from '@angular/core';
import { MockBackend } from '@angular/http/testing';

import {
  Http,
  HTTP_PROVIDERS,
  Response,
  ResponseOptions,
  BaseRequestOptions,
  ConnectionBackend
} from '@angular/http';

import {
  beforeEach, beforeEachProviders,
  describe, xdescribe,
  expect, it, xit,
  async, inject
} from '@angular/core/testing';

import { BookService } from './book.service';

describe('Book Service', () => {
  beforeEachProviders(() => [
    BookService,
    HTTP_PROVIDERS,
    MockBackend,
    BaseRequestOptions,
    provide(Http, {
      useFactory: function (backend:ConnectionBackend, defaultOptions:BaseRequestOptions) {
        return new Http(backend, defaultOptions);
      },
      deps: [MockBackend, BaseRequestOptions]
    })
  ]);

  it('should ...',
      inject([BookService], (service: BookService) => {
    expect(service).toBeTruthy();
  }));

  it('should assign a list of books', inject([BookService, MockBackend, Http], (bookService, backend, http) => {
    backend.connections.subscribe(connection => {
      var mockResponse = new Response(new ResponseOptions({
        body: [{ name: 'Whiteboard Interviews' }]
      }));
      connection.mockRespond(mockResponse);
    });

    let service = new BookService(http);
    service.getList().subscribe(response => {
      expect(response.json()).toEqual([{ name: 'Whiteboard Interviews' }]);
    });
  }));
});