1
私はMockBackendを使用して私のサービスのユニットテストを書いています。MockBackendで角2/4テストサービスが返されます。返り値は未定義です
私は解決策のために、以下のURLを参照し: https://angular.io/api/http/testing/MockBackend
すべてのヘルプは高く評価されます。
は、ここに私のサービスです:あなたはes6.libからの応答を使用していますが角度のhttpから1を必要とするよう
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();
}));
});
返信いただきありがとうございます。しかし、実際の問題は結果が間違った場所で検証されることです。私はそれのように動作しました 'それ( 'login()success'、 inject([XHRBackend、AuthService]、(mockBackend:authService:AuthService)=> { )mockBackend.connections.subscribe((接続:MockConnection)= > { connection.mockRespond(新しい応答(新ResponseOptions({ 体:JSON.stringify(loginData)、 }))); }); authService.login( 'ユーザ名'、 'パスワード') .subscribe (データ=> { 期待する(データ).toBeDefined(); 期待(data.userId).toBeDefined(); 期待(data.token).toBeDefined(); }); }) )。 ' – Vairam
同じ問題を解決するのに役立ちましたので、回答をアップしました。ありがとう – rchavarria