我的 <custom-directive>
有 replace:true
和 template: '<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/