Я пробую ПРОСТОЙ директиву Unit Test, но он не работает. Я получаю: Error: Unexpected request: GET my-directive.html No more request expected
Не уверен, что это значит, он работает на веб-странице...
LIVE DEMO: http://plnkr.co/edit/SrtwW21qcfUAM7mEj4A5?p=preview
directiveSpec.js:
describe('Directive: myDirective', function() {
beforeEach(module('myDirectiveModule'));
var element;
var scope;
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element('<my-directive something="thing"></my-directive>');
element = $compile(element)(scope);
scope.thing = {name: 'My thing'};
scope.$digest();
}));
it('should update the rendered text when scope changes', function() {
scope.thing.name = 'My new thing';
scope.$digest();
var h1 = element.find('h1');
expect(h1.text()).toBe('My new thing');
});
});
app.js:
angular.module('myDirectiveModule', [])
.directive('myDirective', function() {
return {
bindToController: true,
controller: function() {
var vm = this;
vm.doSomething = doSomething;
function doSomething() {
vm.something.name = 'Do something';
}
},
controllerAs: 'vm',
restrict: 'E',
scope: {
something: '='
},
templateUrl: 'my-directive.html'
};
})
.controller('DirCtrl', ['$scope', function() {
this.getName = 'Hello world!';
}]);
Как просто проверить тестовый блок?
Вам нужно высмеять запрос шаблона. Поскольку директива имеет templateUrl
она пытается сделать запрос на получение, но $ http не ожидает никакого запроса, поэтому он терпит неудачу. Вы можете высмеять запрос с ответом или разместить шаблон в службе кеша шаблона.
beforeEach(inject(function($rootScope, $compile, $templateCache) {
$templateCache.put('my-directive.html','<h1 ng-click="vm.doSomething()">{{vm.something.name}}</h1>');
scope = $rootScope.$new();
element = angular.element('<my-directive something="thing"></my-directive>');
element = $compile(element)(scope);
scope.thing = {name: 'My thing'};
scope.$digest();
}));
Кроме того, на вашем it
вызов функции $apply
и использовать $evalAsync
. Смотрите мой раздвоенный плункер.
<my-directive></my-directive>
?$compile
а затем вызов метода$digest