Angular2单元测试Http MockBackend问题 - 无法在mergeOptions读取未定义的属性合并

时间:2015-12-09 13:50:53

标签: javascript angularjs unit-testing http jasmine

Angular2单元测试Http MockBackend问题 - 无法在mergeOptions读取未定义的属性合并。

我试图为我的http获取承诺进行基本单元测试。

typescript编译器工作正常。 但是当我用karma运行器运行npm run test时,我得到以下错误。

这是我得到的gitbash错误:无法读取属性' merge'在mergeOptions中未定义。

这是我的代码:

 import {Injectable} from 'angular2/angular2';
 import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';

 @Injectable()

 export class FirebaseService{
   headers: Headers;

   constructor(public http?: Http) {   
     this.headers = new Headers();
     this.headers.append('Content-Type', 'application/json');
   }

   public getSpotifyTracks = ():Promise<Object> =>{ 
       return this.http
        .get('https://api.spotify.com/v1/tracks/0eGsygTp906u18L0Oimnem', {headers:this.headers})
        .map((response) => {
           return response.json()
        }).toPromise();  
   }
 }

这是我的测试:

 import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit, injectAsync, beforeEachProviders, fakeAsync, tick} from 'angular2/testing';
 import {provide, Injector, bind} from 'angular2/angular2';
 import {HTTP_PROVIDERS, Http, MockBackend, BaseRequestOptions} from 'angular2/http';

 import {FirebaseService} from '../app/firebase-service';

 describe('Spotify Service Calls', () => {
     beforeEachProviders(() => [    
         MockBackend,
         BaseRequestOptions,
         provide(Http, {useFactory:
             function(backend, defaultOptions) {
                 return new Http(backend, defaultOptions);
             },
             deps: [MockBackend]})
     ]);

     //This test doesnt work??????????????
     it('getting tracks', inject([Http], (http) => {
         var firebaseService = new FirebaseService(http);
         var response;

         firebaseService.getSpotifyTracks().then((res) => {
             response = res;
             expect(response).not.toBe(null);
         });
     }));    
 });

1 个答案:

答案 0 :(得分:0)

我已经更新到alpha.46并且它打破了很多东西。有一点是,http.get(...)调用不再返回带有.map方法的Observable。

查看是否用{/ p>替换.map

return this.http
    .get('https://api.spotify.com/v1/tracks/0eGsygTp906u18L0Oimnem', {headers:this.headers})
    .subscribe((response) => {
       return response.json()
    }).toPromise();

这就是我做了什么,它有效,不确定&#34;对&#34;这是......但