Posted at

Angular2でHTTPリクエストのテスト

More than 1 year has passed since last update.

Angular2 v2.0.0 でのテストの書き方が検索してもあまり見つからなかった。

/* tslint:disable:no-unused-variable */

import {TestBed, async, inject} from '@angular/core/testing';
import {ApiService} from './api.service';
import {HttpModule, BaseRequestOptions, Http, Response, ResponseOptions} from "@angular/http";
import {MockBackend, MockConnection} from "@angular/http/testing";

import {User} from "./user";

describe('Service: Api', () => {

beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [ApiService, {
provide: Http,
useFactory: (backend, options) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
}, MockBackend, BaseRequestOptions]
});
});

it('userInfo', async(inject([MockBackend, ApiService], (backend: MockBackend, service: ApiService) => {

backend.connections.subscribe((conn: MockConnection) => {
let ops = new ResponseOptions({body: {name: 'kyusyukeigo'}});
conn.mockRespond(new Response(ops));
});

service.getUser().subscribe((user: User) => {
expect(user).not.toBeNull();
expect(user.name).toBe('kyusyukeigo');
});

})));
});

参考: http://stackoverflow.com/questions/39599084/test-angular-2-0-0-component-with-http-request