这里有几个指令和单元测试.
这是第一个指令:
directive('myTestDirective', function() {
return {
link: function(scope, element, attrs) {
element.on("click", function(e) {
scope.clicked = true;
console.log("clicked");
}
}
});
Run Code Online (Sandbox Code Playgroud)
单元测试:
describe('my test directive', function() {
beforeEach(function() {
.....
inject($compile, $rootScope) {
scope = $rootScope.$new();
html = '<div my-test-directive></div>';
elem = angular.element(html);
compiled = $compile(elem);
compiled(scope);
scope.$digest();
}
});
it('should set clicked to true when click() is called', function() {
elem[0].click();
expect(scope.clicked).toBe(true);
});
});
Run Code Online (Sandbox Code Playgroud)
运行上述单元测试时,测试通过并clicked记录到控制台.
但是,请考虑restrict: E添加以下指令:
directive('myDirective', function() {
return {
restrict: 'E', …Run Code Online (Sandbox Code Playgroud)