我有一个控制器可以从不同的地方更改一些DOM。
控制器是:
angular.module('myModule').controller('myController', myController);
function myController() {
this.addSomeClass = function() {
$('#idOfSomeElement').addClass('someClass');
};
}
它就像这样使用。里面有不同的组件和html。
<div id="idOfSomeElement"></div>
.
.
.
<some-angular-component-here>
<div ng-controller="myController as ctrl">
<div ng-click="ctrl.addSomeClass()"></div>
</div>
</some-angular-component-here>
.
.
.
<using-in-onother-place>
<div ng-controller="myController as ctrl">
<div ng-click="ctrl.addSomeClass()"></div>
</div>
</using-in-onother-place>
我尝试像这样测试它,但我有未定义的ctrl。
describe('Controller test', function () {
'use strict';
var ctrl,
element;
beforeEach(inject(function ($rootScope, $compile) {
var scope = $rootScope.$new();
angular.element('<div id="idOfSomeElement"></div>' +
'<div ng-controller="myController as ctrl">' +
'<div id="button" ng-click="ctrl.addSomeClass()"></div>' +
'</div>');
element = $compile(element)(scope);
scope.$apply();
// how to get controller here with linked to html?
ctrl = $controller('myController');
ctrl = element.controller('myController');
}));
it('should add some class', function () {
var button = $(element).find('#button')[0];
$(button).trigger('click');
var someElement = $(element).find('#idOfSomeElement')[0];
expect(someElement).toHaveSomeClass();
});
});
如何正确测试这种控制器? 我知道在控制器内部操纵DOM是件坏事,但我需要对它进行单元测试。
由于
答案 0 :(得分:0)
我想你忘了将angular.element的返回值赋给你的元素属性......
element = angular.element(....
在每个人之前完成:
beforeEach(inject(function ($rootScope, $compile) {
var scope = $rootScope.$new();
element = angular.element('<div id="idOfSomeElement"></div>' +
'<div ng-controller="myController as ctrl">' +
'<div id="button" ng-click="ctrl.addSomeClass()"></div>' +
'</div>');
element = $compile(element)(scope);
scope.$apply();
// how to get controller here with linked to html?
ctrl = $controller('myController');
ctrl = element.controller('myController');
}));