我在 AngularJS 中有指令,其中包含模块 $document。
$document.click(function (e) {});
我一直在尝试使用 Karma 为其编写单元测试,但它破坏了测试,因为 $document
中不存在函数 click()
,也尝试使用$document
的其他函数如 keyup()
也遇到了同样的问题:
TypeError: undefined is not a function
这是使它失败的测试代码:
describe('Directive: multiSelectMenu', function () {
var element, scope;
beforeEach(module('myApp'));
describe('Test setup', function() {
it ('Injecting required data', inject(function ($compile, $rootScope) {
scope = $rootScope.$new();
element = $compile(angular.element('<div multi-select-menu></div>'))(scope);
$rootScope.$apply();
scope = element.isolateScope();
scope.$apply();
}));
});
});
为什么会失败?
最佳答案
这是the documentation说到 $document:
A jQuery or jqLite wrapper for the browser's window.document object.
如果您单击该链接,您将看到在 jqLite 元素上定义的方法。 click() 和 keyup() 都不在其中。这些方法确实存在于真正的 jQuery 对象上(参见 http://api.jquery.com/category/events/ ),但是如果您在 JS 文件列表中在 angular.js 之前包含 jQuery,AngularJS 只会返回一个 jQuery 对象。
关于angularjs - 为什么在我的测试中所有 $document 函数都未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27126054/