【问题标题】:How to Unit Test a directive which binds from controller如何对从控制器绑定的指令进行单元测试
【发布时间】:2013-12-02 12:50:27
【问题描述】:

我有一个简单的指令,它只是将来自控制器的绑定大写。

我的单元测试代码没有运行。有什么想法吗?

html:

<div ng-controller="MainCtrl as main">

    <div uppercase>{{main.message}}</div>

</div>

控制器:

app.controller('MainCtrl', function(){
    this.message = 'hello world'
})

指令:

app.directive('uppercase', function($timeout) {
    return {
        restrict: 'A',
        transclude: true,
        template: '<span ng-transclude></span>',
        link: function(scope, el, attr) {
            $timeout(function(){
                el.text(el.text().toUpperCase());
            });
        }
    }
});

我目前的单元测试是:

describe("App", function() {

    var $compile
    ,   $rootScope
    ,   $controller
    ,   MainCtrl
    ,   element;

  beforeEach(module('app'))

  beforeEach(inject(function(_$compile_, _$rootScope_, _$controller_){

    $compile = _$compile_;
    $rootScope = _$rootScope_;
    $controller = _$controller_;

    MainCtrl = $controller('MainCtrl');



  }))

  describe("MainCtrl", function() {
    it("should have a message property", function() {
      expect(MainCtrl.message).toBe('hello world');
    });
  });

  describe("Uppercase directive", function() {
    it("should return uppercase text", function() {      

      element = '<p superman>{{MainCtrl.message}}</p>';

      element = $compile(element)($rootScope);

      $rootScope.$digest();

      expect(element.text()).toBe('HELLO WORLD');
    });
  });


});

我不能在我的测试中使用 $timeout,我应该如何测试它?

【问题讨论】:

    标签: unit-testing angularjs karma-runner


    【解决方案1】:

    我没有测试过,但我相信在expect(element.text()).toBe('HELLO WORLD');之前,你必须刷新你的超时时间。

    我的意思是,您将有一个名为 $timeout 的额外变量(在 beforeEach 中),然后,在上述预期之前,您将调用 $timeout.flush()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多