Unit testing nAnimate单元测试未添加类
我不熟悉单元测试以及ng动画模块。我做了一个简单的指令来测试ng动画Unit testing nAnimate单元测试未添加类,unit-testing,angularjs,ng-animate,Unit Testing,Angularjs,Ng Animate,我不熟悉单元测试以及ng动画模块。我做了一个简单的指令来测试ng动画 .directive('slideShow', function ($animate, $compile) { return { template: '<div class="slide-show-container"></div>', restrict: 'EA', replace: true, link: function (scope, e
.directive('slideShow', function ($animate, $compile) {
return {
template: '<div class="slide-show-container"></div>',
restrict: 'EA',
replace: true,
link: function (scope, element, attrs) {
var newElement = $compile('<div class="slide-show-slide"></div>')(scope);
element.bind('mouseenter',function() {
element.append(newElement);
$animate.addClass(newElement, 'slide-enter');
});
element.bind('mouseleave',function() {
$animate.removeClass(newElement, 'slide-enter');
});
}
};
});
当我在手动测试中将鼠标移到该类上时,该指令正确地添加了该类。但是,单元测试失败,并显示没有添加幻灯片输入类
最后,我找到了修复它的唯一方法,那就是在$timeout中包装单元测试:
it('should add slide-enter class', inject(function ($timeout) {
element.triggerHandler( "mouseenter" );
$timeout(function() {
expect(element.children().hasClass("slide-enter")).toEqual(true);
});
$timeout.flush();
}));
有人能帮我理解为什么测试需要这个$timeout吗?有没有其他方法可以让这个单元测试正常工作?请注意,我使用的是angular animate 1.2.0-rc.2,并在这个版本中记录了我的发现。查看1.2.0-rc.3代码时,
$timeout.flush()
调用的需要似乎是固定的,但我还没有测试它
我的一次测试也有同样的问题。在调用本应触发类添加的代码之后,在调用
expect
之前,我只需调用$timeout.flush()
,就可以让测试正常工作。如果您按照以下方式重写测试,则测试应能正常工作:
it('should add slide-enter class', inject(function ($timeout) {
element.triggerHandler( "mouseenter" );
$timeout.flush();
expect(element.children().hasClass("slide-enter")).toEqual(true);
}));
我必须深入研究ngAnimate代码才能找到答案,这就是我发现的
如果您查看addClass
函数中的angular animate.js
文件。您将看到以下内容:
addClass : function(element, className, done) {
performAnimation('addClass', className, element, null, null, function() {
$delegate.addClass(element, className, done);
});
}
performAnimation
的最后一个参数闭包将最终添加类
在执行信息中,最后一个参数名为“onComplete”。有一段代码处理在应跳过动画时调用此闭包:
//skip the animation if animations are disabled, a parent is already being animated
//or the element is not currently attached to the document body.
if ((parent.inheritedData(NG_ANIMATE_STATE) || disabledAnimation).running) {
//avoid calling done() since there is no need to remove any
//data or className values since this happens earlier than that
//and also use a timeout so that it won't be asynchronous
$timeout(onComplete || noop, 0, false);
return;
}
还有对
$timeout
的调用导致了问题。在角度测试中运行此代码时,对$timeout
的调用只是将闭包排队。然后,测试代码必须调用$timeout.flush()
,才能运行该函数。做得不错!这就解释了一切。很高兴看到它在新版本中似乎得到了修复。
//skip the animation if animations are disabled, a parent is already being animated
//or the element is not currently attached to the document body.
if ((parent.inheritedData(NG_ANIMATE_STATE) || disabledAnimation).running) {
//avoid calling done() since there is no need to remove any
//data or className values since this happens earlier than that
//and also use a timeout so that it won't be asynchronous
$timeout(onComplete || noop, 0, false);
return;
}