2017-08-13 4 views
1

コンストラクタにコードを追加しましたが、ユニットテストに失敗しました。新しいコードは、観察からthis.isFollowOnModeにtrueまたはfalseに設定します。ジャスミンで観測値をユニットテストする方法

import { CustomerGroupService } from 'customerGroup.service'; 

class HeaderBarController { 
    private isFollowOnMode: boolean; 

    constructor(private customerGroupService: CustomerGroupService) { 
     'ngInject'; 

     //new code that is causing test to fail: 

     this.customerGroupService.isFollowOnMode$ // will be true or false 
      .subscribe((isFollowOnMode) => { 
       this.isFollowOnMode = isFollowOnMode; 
      }); 
    } 

    // other stuff 
} 

export default HeaderBarController; 

私は私のユニットテストでは、次のエラーを取得:

PhantomJS 2.1.1 (Mac OS X 0.0.0) Controller: HeaderBarController should be defined FAILED TypeError: undefined is not a constructor (evaluating 'this.customerGroupService.isFollowOnMode$'

そして、これが失敗している私のユニットテストです:

describe('Controller: HeaderBarController', function() { 
    beforeEach(angular.mock.module(module.name)); 

    beforeEach(angular.mock.module(function ($provide) { 
     $provide.service('customerGroupService',() => { }); 

    })); 

    beforeEach(inject(function ($rootScope, $componentController) { 
     this.$scope = $rootScope.$new(); 
     this.ctrl = $componentController('headerBar', 
      { 
       // locals 
       $scope: this.$scope, 
       $element: [{}], 
       $attrs: [], 
      }, 
      { 
       // scope bindings 
      } 
     ); 
    })); 

    it('should be defined', function() { 
     expect(this.ctrl).toBeDefined(); 
    }); 

}); 

だから、私はthis.customerGroupService.isFollowOnMode$を設定していないようです。そのデフォルト値はfalseでなければなりません。単体テストで私は単体テストに慣れていないので、どんな助けも素晴らしいでしょう。ありがとう。

+1

物事が変更されない限り、TypeScript/ESNextソースコードの '' ngInject''は信頼できないことがわかっています。 'HeaderBarController {static $ inject = ['customerGroupService'];」と書くと、より堅牢になるでしょう。代わりに、デコレータを使って注釈を自動的に作成することができます。 –

答えて

1

この問題は、オブザーバブルに固有の問題ではなく、一般にサービススタブに適用されます。

この

$provide.service('customerGroupService',() => {}); 

も、それは代わりに、コンストラクタの矢印を使用して正しくないですが、期待される特性なしのサービスになります。

ngMockはすでにサービスを模擬するための方法を提供しています:

let customerGroupServiceMock; 

beforeEach(() => { 
    customerGroupServiceMock = { 
    isFollowOnMode$: Observable.of(true); 
    }; 
    angular.mock.module({ customerGroupService: customerGroupServiceMock }); 
}); 

代わりに、直接注入器でそれらを定義するのコントローラに嘲笑のサービスを注入することも可能です:

this.ctrl = $componentController('headerBar', 
     { 
      // locals 
      customerGroupService: customerGroupServiceMock, 
      $scope: this.$scope, 
      $element: [{}], 
      $attrs: [], 
     }, 

これはまさに「地元の人々であります'を意味する。

+0

これは機能しました。説明してくれてありがとう。 –

+0

ようこそ。 – estus

関連する問題