我有一些指令而不使用任何模板/ templateUrl。如何为该指令编写单元测试。以下代码是我的指示。
var app = angular.module('SampleDirective');
app.directive('sampleContent', [function () {
return {
restrict: 'A',
scope: {
content: '@'
},
link: function (scope, element, attrs) {
var eventHandlers = [];
function onContentChanged(value) {
if (value) {
element.html('');
element.append(value);
}
}
function onDestroy() {
angular.forEach(eventHandlers, function (callback) {
callback();
});
element.remove();
}
eventHandlers.push(scope.$watch('content', onContentChanged));
eventHandlers.push(scope.$on("$destroy", onDestroy));
}
};
}]);
任何人都可以建议我如何为这个样本编写单元测试..
答案 0 :(得分:0)
我已经为上面的代码编写了单元测试..它是否正确?
describe("sampleContent", () => {
let scope;
let compile;
let element;
beforeEach(angular.mock.module("SampleDirective"));
beforeEach(() => {
inject(($compile, $rootScope) => {
scope = $rootScope;
compile = $compile("<input sample-content=\"ContentValue\"></input>");
element = compile(scope);
});
});
describe("onContentChanged", () => {
it("should validate onContentChanged when the value is a valid content", () => {
scope.$$childHead.content = "This is a sampleContent";
scope.$digest();
expect(element[0].textContent).toEqual("This is a sampleContent");
});
it("should validate onContentChanged when the value is not a valid content", () => {
scope.$$childHead.content = undefined;
scope.$digest();
expect(element[0].textContent).toEqual("");
});
});
});