【问题标题】:How to write unit test case for scope and timeout function inside directive如何在指令内编写范围和超时功能的单元测试用例
【发布时间】:2016-07-21 09:30:41
【问题描述】:

我在自定义指令中使用了隔离范围。我已经更新了 plunker 链接。 http://plnkr.co/edit/NBQqjxW8xvqMgfW9AVek?p=preview 有人可以帮我编写 script.js 文件的单元测试用例吗?

script.js

var app = angular.module('app', [])

app.directive('myDirective', function($timeout) {
  return {
    restrict: 'A',
    scope: {
      content: '='
    },
    templateUrl: 'my-directive.html',
    link: function(scope, element, attr) {

      $timeout(function() {
        element = element[0].querySelectorAll('div.outerDiv div.innerDiv3 p.myClass');
        var height = element[0].offsetHeight;
        if (height > 40) {
          angular.element(element).addClass('expandable');
          scope.isShowMore = true;
        }
      })


      scope.showMore = function() {
        angular.element(element).removeClass('expandable');
        scope.isShowMore = false;
      };

      scope.showLess = function() {
        angular.element(element).addClass('expandable');
        scope.isShowMore = true;
      };
    }
  }
})

(function() {
  'use strict';

  describe('Unit testing directive', function() {
    var $compile, scope, element, compiledDirective, $rootScope, $timeout;

    beforeEach(module("app"));
    beforeEach(inject(function(_$compile_, _$rootScope_, _$timeout_) {
      $compile = _$compile_;
      scope = _$rootScope_.$new();         
      $timeout = _$timeout_;
      element = angular.element(' <div my-directive content="content"></div>');
      compiledDirective = $compile(element)(scope);
      scope.$digest();
    }));

    it('should apply template', function() {
      expect(compiledDirective.html()).toBe('');
    });

    it('check for timeout', function() {
      $timeout.flush();
    });

  });
})();

【问题讨论】:

    标签: angularjs unit-testing


    【解决方案1】:

    使用 $timeout.flush() 函数为 $timeout 编写测试用例

    it('check for timeout', function() {
    
        scope.digest();
    
        // flush timeout(s) for all code under test.
        $timeout.flush();
    
        // this will throw an exception if there are any pending timeouts.
        $timeout.verifyNoPendingTasks();
    
        expect(scope.isShowMore).toBeTruthy();
    });
    

    Check this article for better understanding.

    【讨论】:

      猜你喜欢
      • 2015-11-28
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      相关资源
      最近更新 更多