我正在测试一个Angular指令的单元,而且这个测试在过去与Angular 1.4.9一起工作。我最近升级到1.5.0,所以我认为这个问题/(意外的结果)可能是由于angular-mocks
。Jasmine角度指令被编译为一个对象
describe('The buttonToggle directive', function() {
var $compile,
btElement = '<button-toggle></button-toggle>',
compiledElement,
btElementPath = 'button-toggle.html',
$scope;
beforeEach(inject(function(_$compile_, $templateCache, $rootScope) {
$compile = _$compile_;
$scope = $rootScope.$new();
var template = $templateCache.get(btElementPath);
$templateCache.put(btElementPath, template);
var element = angular.element(btElement);
compiledElement = $compile(element)($scope);
console.log(compiledElement);
$scope.$digest();
console.log(compiledElement);
}));
it('should compile', function() {
expect(compiledElement.html()).toContain('btn');
});
});
compiledElement
刚刚被放入一个对象。下面是从console.log
返回值:
{0: <button-toggle class="ng-scope"></button-toggle>, length: 1}
我不明白为什么会这样。它应该被编译成button-toggle.html
的内容。
编辑:忘记在beforeEach注入buttonToggle模块。我是否也需要注入主应用程序模块?如果我插入它,然后我得到一个undefined is not an object (evaluation compiledElement.html)
。
模块注射:
beforeEach(module('ocapp.buttonToggle'));
beforeEach(module('ocapp'));
编辑2:我不再认为这是一个angular-mocks
版本问题。我的指令取决于在单独的文件中定义的控制器,并且它没有被解析。
按钮toggle.directive.js
button-toggle.html
是在同一个目录中的所有其他文件在这里使用的,也许我并不需要在格兰templateUrl
属性扩展路径?
编辑3:我已经解决了所有其他问题并回到了原点。
按钮toggle.directive.spec.js
describe('The buttonToggle directive', function() {
var $compile,
btElement = '<button-toggle></button-toggle>',
compiledElement,
btElementPath = 'app/button-toggle/button-toggle.html',
$scope,
$httpBackend;
beforeEach(module('ocapp.buttonToggle'));
//beforeEach(module('ocapp'));
beforeEach(inject(function(_$compile_, $templateCache, $rootScope, $injector) {
$compile = _$compile_;
$scope = $rootScope.$new();
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET(btElementPath).respond(200, '');
var template = $templateCache.get(btElementPath);
$templateCache.put(btElementPath, template);
var element = angular.element(btElement);
compiledElement = $compile(element)($scope);
console.log(compiledElement);
$scope.$digest();
}));
it('should compile', function() {
expect(compiledElement.html()).toContain('btn');
});
});
参见this question and accepted answer对于如何从在一个指令同一个模块定义一个外部控制器。
按钮toggle.directive.js
(function() {
'use strict';
angular
.module('ocapp.buttonToggle')
.directive('buttonToggle', buttonToggle);
function buttonToggle() {
return {
restrict: 'E',
templateUrl: 'app/button-toggle/button-toggle.html',
replace: true,
scope: {
on: '='
},
controller: 'ButtonToggleController'
};
}
})();
请确保您还用角嘲笑1.5 –
Yessir,我。忘了注入模块,但现在我收到了一个不同的错误。 – Healforgreen