基本服务测试

时间:2016-04-08 20:38:31

标签: angular karma-jasmine

我有一项服务:

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

什么是好方法?

1 个答案:

答案 0 :(得分:4)

实际上要测试你的LoginService,你需要模拟它的依赖关系,而不是服务本身。在这种情况下,您需要将XHRBackend类替换为MockBackend一个。

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

然后,您可以注入XHRBackend并订阅其connections属性以拦截请求并返回您自己的回复。

以下是一个名为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());
  }
}