我们有一个定义此函数的 AngularJS Controller :
$scope.testMe = function() {
return $('#test');
}
现在我们如何测试它?
我们的尝试是这样的 Karma 测试:
describe('testMe', function() {
var scope, element, ctrl;
var html = '<span id="test"></span>';
beforeEach(module('theModule'));
beforeEach(inject(function($rootScope, $compile, $controller) {
scope = $rootScope.$new();
ctrl = $controller('theCtrl', {$scope: scope});
element = $compile(html)(scope);
}));
it('finds it', function() {
var gotcha = scope.testMe();
expect(gotcha.attr('id')).toBe('test');
});
});
...但它不起作用 - jQuery 似乎在 Karma 生成的 DOM 中查找,而不是在我们在 var html
中定义的 DOM...
最佳答案
我认为将您创建的元素附加到 Karma 的 DOM 中不会导致任何问题。 你可以这样做:
$("body").append($compile(html)(scope));
scope.$digest();
如果你不想弄乱 Karma 的 DOM,也许可以尝试 html2js preprocessor在这个问题中建议:Load HTML files with Karma
关于javascript - 使用 DOM 的 Angular Controller 中的测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23655607/