如何在Jasmine单元测试中使用Sinon伪造jQuery动画? [英] How do I fake-time a jQuery animation using Sinon in a Jasmine unit test?

查看:161
本文介绍了如何在Jasmine单元测试中使用Sinon伪造jQuery动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有1秒jQuery .animate 操作,在页面加载后5秒启动。我在我的Jasmine单元测试代码中设置了一个Sinon计时器,并在7秒钟后测试,以查看动画后的属性是否正常。

I have a 1 second jQuery .animate action that launches 5 seconds after page load. I set up a Sinon timer in my Jasmine unit testing code and test after a tick of 7 seconds to see if the post-animation properties are as they should be.

It不能正常工作,所以我在Jasmine HTML测试页面上放置了一个动画实例,以便更好地了解正在发生的事情。

It doesn't work right, so I've placed an instance of the animation itself on my Jasmine HTML test page to better see what's going on.


  • 在Firefox和Chrome中,页面加载,动画函数被调用,单元测试立即失败,然后(也立即)动画明显发生。

  • In Firefox and Chrome, the page loads, the animation function is called, the unit test immediately fails, and then (also immediately) the animation visibly occurs.

在IE,Opera和Safari中,页面加载,动画函数被调用,单元测试立即失败,动画永远不会明显发生。

In IE, Opera and Safari, the page loads, the animation function is called, the unit test immediately fails, and the animation never visibly occurs.

我希望的是以下(在所有浏览器中):

What I hoped for was the following (in all browsers):


  • 页面加载,动画函数被调用,动画立即完成,单元测试立即成功。

查看 Sinon的文档,它的假定时器涵盖以下过程:
setTimeout clearTimeout setInterval clearInterval 日期

Looking at Sinon's documentation, it's fake timers cover the following processes: setTimeout, clearTimeout, setInterval, clearInterval, Date

我不知道jQuery的动画是如何工作的,但我想它正在使用CSS进行转换,并且Sinon的 useFakeTimers ,所以我想这就是问题所在。但是,如果我对这个问题是对的,我仍然需要一个解决方案。

I don't know how jQuery's animation works, but I imagine it is using CSS to transition, and CSS transitions are not covered in Sinon's useFakeTimers, so I imagine this is the problem. However, if I'm right about the problem I still need a solution.

也许我应该尝试除了Sinon以外的其他东西? Jasmine的等待()在这个测试中表现完美,但对于像我这样的不耐烦的人来说是非常不切实际的。

Maybe I should try something other than Sinon? Jasmine's waits() works perfectly in this test, but is incredibly impractical for impatient folks like myself.

任何其他建议?请记住,我是JS单元测试的新手,所以模糊的答案会让我更加困惑,而不是帮助我。 ; o)

Any other suggestions? Please keep in mind that I am new to JS unit testing, so vague answers will confuse me more than help me. ;o)

推荐答案

您可以使用 jQuery off 关闭jQuery效果:

You can use jQuery off to turn off jQuery effects:

jQuery.fx.off = true

这不会解决你的事件发生的第7次等待的问题但是它确实意味着您可以测试DOM已按预期更改。

This won't solve your problem of the inital 7 second wait for your event to fire but it does mean you can test that the DOM has been changed as you expected.

这篇关于如何在Jasmine单元测试中使用Sinon伪造jQuery动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆