私の技術:角バージョン4、webpack、karma、ジャスミンとtypescriptのユニットテスト。http取得リクエストのための基本的な角度2ユニットテストをしたい
httpコールを持つサービス機能をテストする方法の基本的な例が必要です。
これが私の基本的なサービスである:
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
@Injectable()
export class TestService {
headers: Headers;
http: Http;
constructor(http: Http) {
this.http = http;
this.headers = new Headers();
}
test =(): Promise<boolean> => {
return new Promise((resolve, reject) => {
const url = 'http://www.ipsumlorem.com/json';
this.http.request(url).subscribe(response => {
resolve(true);
});
});
}
};
これはそれのための私の現在の仕様(ユニットテスト)である:例作業
import { TestService } from './test.service';
import {Injectable, ReflectiveInjector} from '@angular/core';
import {async, fakeAsync, tick, inject, TestBed} from '@angular/core/testing';
import {BaseRequestOptions, ConnectionBackend, Http, ResponseOptions, Response, HttpModule} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';
let service;
describe('Service : testService',() => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
TestService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory: (mb:MockBackend, opts:BaseRequestOptions) => {
return new Http(mb, opts);
}
}
],
imports: [HttpModule]
}).compileComponents();
});
beforeEach(inject([Http], (http: Http) => {
service = new TestService(http);
}));
it('should call test function and return a promise with value true', async(() => {
//Mock response
TestBed.get(MockBackend).connections.subscribe(c => {
c.mockRespond(new Response(new ResponseOptions({body: Promise.resolve(true)})));
});
let result = true;
service.test().then((response: any) => result);
expect(result).toEqual(true);
}));
});
既に[MockBackend](https://angular.io/docs/ts/latest/api/http/testing/index/MockBackend-class.html)のドキュメントを参照していますか?そこにリストされている非常に良い詳細な例があります。 – Igor
URLが壊れているようです@Igor - https://angular.io/api/http/testing/MockBackend –