gpt4 book ai didi

javascript - 使用 DOM 的 Angular Controller 中的测试函数

转载 作者:行者123 更新时间:2023-12-02 17:23:58 24 4
gpt4 key购买 nike

我们有一个定义此函数的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com