2
我有這樣一種服務:基本服務測試
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);
}));
});
什麼是一個好方法?
再次感謝您,亨利,我想你的例子:這個問題是我得到的錯誤:失敗:httpService.getMethod不是一個函數... –
你在'HttpService'類上有'getMethod'方法嗎? –
所以我不知道我做了什麼,但:根據你的回答,我試着https://github.com/krimple/angular2-webpack-demo-routing-and-http。我有同樣的問題。然後我看了一下服務,我注意到有一個導入有'rxjs/add/operator/map';我補充說,服務和工作! –