1
我正在爲使用MockBackend的服務編寫單元測試,每次我都以{}的形式獲得響應。使用MockBackend的角度2/4測試服務返回undefined
我稱爲下面的網址爲溶液: https://angular.io/api/http/testing/MockBackend
任何幫助理解。
這裏是我的服務:
import {Injectable} from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import {LoginResult} from './models';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
private _loginUrl = '/api/login';
private _logoutUrl = '/api/logout';
private headers = new Headers({ 'Content-Type': 'application/json' });
private options = new RequestOptions({ headers: this.headers });
private _isAuthenticated:boolean;
constructor(private _http:Http) {}
isAuthenticated():boolean {
return this._isAuthenticated;
}
setUserLoggedIn(authStatus: boolean) {
this._isAuthenticated = authStatus;
}
login(username:string, password:string) {
let body = JSON.stringify({username: username, password: password});
return this._http.post(this._loginUrl, body, this.options)
.map(res => res.json());
}
}
這裏是我的測試:
import {async, fakeAsync, TestBed, tick} from '@angular/core/testing';
import { HttpModule, Http, ConnectionBackend, XHRBackend, RequestOptions, BaseRequestOptions, ResponseOptions} from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { ReflectiveInjector } from '@angular/core';
import { AuthService } from './auth.service';
import { LoginResult } from './models';
export const loginData = {
"userId": "593732e2d3d20e1b852dc463",
"username": "xyz",
"roles": [
"ROLE1",
"ROLE2"
],
"token": "e26c2b7b-c60f-404d-94d5-d35446fd2a9c"
};
describe('AuthService',() => {
beforeEach(() => {
this.injector = ReflectiveInjector.resolveAndCreate([
{provide: ConnectionBackend, useClass: MockBackend},
{provide: RequestOptions, useClass: BaseRequestOptions},
Http,
AuthService
]);
this.authService = this.injector.get(AuthService);
this.backend = this.injector.get(ConnectionBackend) as MockBackend;
t his.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
});
it('login should query current service url',() => {
this.authService.login('username', 'password');
expect(this.lastConnection).toBeDefined('no http service connection t all?');
expect(this.lastConnection.request.url).toMatch(/api\/login$/, 'url invalid`');
});
it('login', fakeAsync(() => {
let result: any;
this.authService.login('username', 'password')
.subscribe(response => {
console.log('Response :::' + JSON.stringify(response));
result = response;
})
this.lastConnection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(loginData),
})));
tick();
expect(result).toBeDefined();
}));
it('login while server is down', fakeAsync(() => {
let result: LoginResult;
let loginError: any;
this.authService.login('username', 'password')
.subscribe(response => {
console.log('Response1 :::' + JSON.stringify(response));
result = response;
}, (error: any) => { loginError = error; });
this.lastConnection.mockRespond(new Response(new ResponseOptions({
status: 404,
statusText: 'URL not found.'
})));
tick();
expect(result).toBeUndefined();
expect(loginError).toBeDefined();
}));
});
感謝您的回覆。但真正的問題是結果在錯誤的地方被證實。我得到了這樣的工作:'it('login()success', inject([XHRBackend,AuthService],(mockBackend:MockBackend,authService:AuthService)=> {mockBackend.connections.subscribe((connection:MockConnection)= > { connection.mockRespond(新響應(新ResponseOptions({ 體:JSON.stringify(loginData) }))); }); authService.login( '用戶名', '密碼') .subscribe (數據=> { 期望(數據).toBeDefined(); 期望(data.userId).toBeDefined(); 期望(data.token).toBeDefined(); });} ) ); ' – Vairam
Upvoting的答案,因爲它幫助我找到同樣的問題的解決方案,謝謝 – rchavarria