AngularJS 测试替换设置为 true 的指令

标签 angularjs unit-testing angularjs-directive

我的 <custom-directive>replace:truetemplate: '<img />' .
如何为它编写单元测试?我想我想测试它是否真的用 img 替换了自定义指令。

it('should be transformed to <img>', function(){
  var elm = $compile('<custom-directive></custom-directive>')(scope);
  scope.$digest();

  var t = elm.find('img'); // wrong! it replaces the element. it won't find another one inside
 //expect(elm).toBeAnImgElement ?
});

我找不到正确的匹配器。
我见过的最接近的情况是检查内容( elm.html()elm.text() )但我的标签是空的。

最佳答案

将您的指令包装在一个 div 中,例如:

describe('Directive: custom', function () {
  beforeEach(module('App'));

  var element, $scope;

  it('should be transformed to <img>', inject(function ($rootScope, $compile) {
    $scope = $rootScope.$new();
    element = angular.element('<div><custom-directive></custom-directive></div>');
    element = $compile(element)($scope);

    expect(element.children('img').length).toBe(1);
  }));
});

关于AngularJS 测试替换设置为 true 的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16362681/

相关文章:

angularjs - 如何在 AngularJS 中使用按键事件?

angularjs - Ag-grid 自定义过滤器 : filterParams - cellRenderer in Angular 1. x

javascript - 如何在 angularjs 中同时执行 $http

javascript - 通过 bool 属性使用 “track by” 过滤 Angular ng-repeat

angularjs:将焦点设置在指令内先前隐藏的输入元素上

angularjs - 检测图像是从指令完全加载的,其中指令未应用于图像元素

javascript - 了解 ng-table 演示中的延迟排序示例

c# - 开始在现有代码库中进行自动化集成/单元测试

c# - 为什么我不能更改 Rhino Mocks stub 对象中的返回值?

django - 如何从所有应用程序加载 Django 装置?