我有一个 Angular 应用程序,它有一个非常简单的指令,现在称为 animate。我正在尝试使用 Jasmine 检查是否调用了 SlideDown 方法。目前我的指令如下所示:
animateDirective
var animate = function () {
return function (scope, element, attrs) {
scope.$watch(attrs.animate, function () {
element.slideDown(200);
})
}
}
应用程序
var app = angular.module("app", []);
app.controller("homeController", homeController);
app.directive("animate", animate);
在我的单元测试文件中,我检查了所有引用是否正确,并且我在浏览器中进行了测试,并且指令被命中。这是到目前为止我的单元测试类:
animateDirectiveUnitTests
describe("animateDirective", function () {
var $compile;
var $scope;
var template = "<p animate></p>";
var isolateScope;
function createDirective() {
var directiveElement = angular.element(template);
$compile(directiveElement)($scope);
$scope.$digest();
return directiveElement;
}
beforeEach(function () {
module("app");
inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$scope = _$rootScope_.$new();
});
});
it("should call slideDown", function () {
var element = createDirective();
spyOn(element, "slideDown");
expect(element.slideDown).toHaveBeenCalled();
})
});
我从测试结果中得到的错误消息是:“预期 spy slideDown已被调用”。我还尝试更改我的测试以引用 jQuery 对象,如下所示,但我得到了相同的错误:
var element = createDirective();
spyOn($.fn, "slideDown");
expect($.fn.slideDown).toHaveBeenCalled();
我不确定为什么这没有注册为调用。是否有可能做到这一点?如果是这样,我将不胜感激一些关于使其发挥作用的指导。谢谢
最佳答案
您的测试用例流程似乎错误。
var element = createDirective();
spyOn($.fn, "slideDown");
expect($.fn.slideDown).toHaveBeenCalled();
在此代码中,在创建 spy 和检查期望之间没有任何内容可以执行 - 因此没有任何内容可以调用 slipDown。
什么应该调用slideDown?您应该首先创建元素,将 spy 放置在其上,然后触发最终调用slideDown的更改 - 在完成所有这些之后,按照这个顺序,您应该能够在您的测试。
关于JavaScript 单元测试 : Cannot check if jQuery method was called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28583479/