###前提・実現したいこと
angularのユニットテストで外部サーバで公開されているAPIを実行して、結果をテストしたい。
モックを使う方法はサンプルコードが多数あるが、今回は直接外部のサーバAPIにアクセスしたい。
###発生している問題・エラーメッセージ
http.getが実行できず、以下のエラーメッセージが表示される
ng test Failed: Cannot read property 'get' of undefined TypeError: Cannot read property 'get' of undefined
###該当のソースコード
angular
1import { TestBed, inject, async } from '@angular/core/testing'; 2 3import { MockBackend, MockConnection } from '@angular/http/testing'; 4import { 5 Http, HttpModule, Response, ConnectionBackend, 6 RequestOptions, BaseRequestOptions, ResponseOptions 7} from '@angular/http'; 8 9import { Injectable } from '@angular/core'; 10 11describe('APIテスト', () => { 12 beforeEach(() => { 13 TestBed.configureTestingModule({ 14 providers: [ 15 {provide: Http, apiServiceFactory: (backend, options) => new Http(backend, options), deps: [ MockBackend, BaseRequestOptions ]}, 16 MockBackend, 17 BaseRequestOptions, 18 ] 19 }); 20 }); 21 22 it('データが存在するか?', async(inject([ Http ], (http: Http) => { 23 http.get('http://xxx.com/api/getData?key=10') 24 .subscribe( 25 res => { 26 expect(res).toEqual(null) 27 } 28 ) 29 }))) 30});
###試したこと
- MockBackendをConnectionBackendに変更した
- let http = new Http(Mockbackend, BaseRequestOptions)と直接インスタンスを作って試した
###補足情報(言語/FW/ツール等のバージョンなど)
angular 4.2.4
あなたの回答
tips
プレビュー