AngularJS测试指令,将replace设置为true

Edu*_*nal 6 unit-testing angularjs angularjs-directive

<custom-directive>replace:truetemplate: '<img />'.我怎样才能为它编写单元测试?我想我想测试它实际上用img替换了custom-directive.

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 ?
});
Run Code Online (Sandbox Code Playgroud)

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

cod*_*mer 18

将您的指令包装在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);
  }));
});
Run Code Online (Sandbox Code Playgroud)