5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?