【问题标题】:Can't unit test my angular.js directive无法对我的 angular.js 指令进行单元测试
【发布时间】:2014-04-04 16:05:52
【问题描述】:

我无法成功地对我的 angular.js 指令(karma + jasmine)进行单元测试...

基本上,在我的指令的编译函数中,我确实将元素内容替换为表单。
进行单元测试时,在

之后
scope = $rootScope;
element = angular.element('<my-directive></my-directive>');
$compile(element)($rootScope);
scope.$digest();

我希望找到包含我的表单的元素,带有'... abc ...'...
事实并非如此...... :-(

这是我的(简化的)指令:

angular.module('myApp')
  .directive('myDirective', function() {
    return {
      restrict: 'E',
      scope: {},
      compile: function(element) {
        element.replaceWith('<form> ... abc ... </form>');
      }
    };
  });

这是我的测试:

describe('Directive: paypalButton', function () {

  beforeEach(angular.mock.module('myApp'));

  var element, scope;

  beforeEach(inject(function ($rootScope, $compile) {
    scope = $rootScope;
    element = angular.element('<my-directive></my-directive>');
    $compile(element)($rootScope);
    scope.$digest();
  }));

  it('replaced content should contain abc', function() {
    expect(element.html()).toContain('abc');
  });

});

该指令有效(在浏览器中我看到“abc”),但“预期”测试总是失败:我在元素的 html() 中没有得到 'abc',但总是得到 'xyz'...

我确定我遗漏了一些明显的东西...... :-(

【问题讨论】:

    标签: angularjs angularjs-directive karma-runner


    【解决方案1】:

    我将编写如下测试。演示PLUNKER

    describe('Directive: paypalButton', function () {
      var element, scope, $compile;
    
      beforeEach(function(){
          module('myApp');
    
          inject(function ($rootScope, $compile) {
              scope = $rootScope;
              element = angular.element('<my-directive></my-directive>');
              $compile(element)(scope);
          });
      });
    
      it('replaced content should be abc', function() {
          element.scope().$digest();
    
          expect(element.text()).toEqual(' ... abc ... ');
      });
    });
    

    随着指令的这种变化:

    app.directive('myDirective', function() {
        return {
          restrict: 'E',
          scope: {},
          compile: function(element) {
              element.append('<form> ... abc ... </form>');  
          }
        };
      });
    

    注意:-

    • 我认为在测试时它不喜欢完全替换元素,因为指令范围绑定到该元素。您可以在元素上尝试append()
    • 此外,由于您在指令中使用了隔离作用域,因此必须在隔离作用域中启动摘要循环。因此,element.scope().$digest();

    【讨论】:

    • 另一点是 toEqual() 与 toBe() 相比也很重要。如果它不是同一个对象,那么您应该检查 toEqual,就像 dmahapatro 所做的那样。您也可以使用 contains() 进行检查。
    • @Asta 你说得对, contains() 是正确的方法......但这不是重点。
    • @dmahapatro:谢谢!我想你的回答是正确的......我现在在工作中使用量角器“与页面同步”有问题,不知道问题是什么......我一回到家(我有一个 headed linux box,并且量角器正常工作)我会测试你的答案...我必须说我终于可以看到一个成功的测试,只是在
      中包含
      ...
      > 标签...我想它与量角器的“root.element”默认值(一个“
      ”...)有关。
    猜你喜欢
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2015-04-03
    • 2017-08-08
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多