2017-08-13 49 views
1

我已经向构造函数添加了一些代码,现在我的单元测试失败了。新的代码从可观察到的设置为true或false来this.isFollowOnMode如何用茉莉花单元测试观察点

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''已知是不可靠的。编写'class 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