基础服务测试

Basic service test

我有这样的服务:

login.service.ts

import { Injectable } from 'angular2/core';
import { Http, Response, Headers } from 'angular2/http';
import { Config } from '../common/config';

@Injectable()
export class LoginService {

    constructor(public http: Http) { }
    response: JSON;
...

    getAuthenticate( username, password ) {
        let headers = new Headers();
        const REST_BASE_URL = Config.GET_REST_BASE_URL;
        let query = '?userid=' + username + ' +&action=authenticate&password=' + password;
        headers.set('Accept', 'application/json');
        return this.http.get(REST_BASE_URL + query, {
        headers: headers
         }).map((res: Response) => res.json());
    }
}

我需要为例如getAutenticate() 方法。不知道我应该如何注入 Http(模型与真实的休息服务)。这是我的出发点:

import { it, describe, expect, inject, beforeEachProviders} from 'angular2/testing';
import {Http} from 'angular2/http';
import { LoginService } from './login.service';

class MockLoginService extends LoginService {
    // todo something
}

describe('login service', () => {
    beforeEachProviders(() => [
        provide(TestService, {useClass: MockLoginService}), Http
  ]);

    // beforeEachProviders(() => [LoginService, Http]);
    it('should find credentials', inject([LoginService], (myService:MockLoginService) => {
        console.log('HERE ', myService.getAutenticate('user1', 'pass1'));
        expect(true).toBe(true);
    }));
});

什么是好的方法?

事实上,要测试您的 LoginService,您需要模拟其依赖项而不是服务本身。在这种情况下,您需要将 XHRBackend class 替换为 MockBackend

beforeEachProviders(() => {
    return [
  HTTP_PROVIDERS,
  provide(XHRBackend, { useClass: MockBackend }),
        HttpService
    ];
});

然后您可以注入 XHRBackend 并订阅其 connections 属性 以拦截请求和 return 您自己的响应。

这是一个示例,其中包含名为 HttpService 的服务:

it('test HTTP service', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
    mockBackend.connections.subscribe(
        (connection: MockConnection) => {
            connection.mockRespond(new Response(
                new ResponseOptions({
                    body: ['some content']
                })));
    });

    httpService.getMethod().subscribe(
        items => {
            expect(items).toEqual(['test']);
        },
        () => {
            console.log('error');
        });
}));

HttpService 可能如下:

@Injectable()
export class HttpService {
  constructor(private http:Http) {
  }

  getMethod() {
    return this.http.get('/test').map(res => res.json());
  }
}