[英]Jasmine - wait for fadeOut() to finish
我有一个简单的函数,它在一个元素中淡入:
码
checkLengthSelect: function(){
if($(this).val() != ''){ // if not empty
$('.c--error').fadeOut('fast', function(){
$('#button').fadeIn();
})
} else { // if empty hide button and show error message
$('#button').fadeOut('fast', function(){
$('.c--error').html('foo').fadeIn(); // <-- I want to test this on fadeOut callback
})
}
},
我正在尝试为此编写一个测试:
测试
it("it should have a value or hide continue button", function(){
// check cover length on select
$(document).on('change', '#select', function(){ qqw.validate.checkLengthSelect.call(this) } );
// force a change event to fire with empty value.
$('#select').val('').change();
setTimeout(function(){
expect($('.c--error').html()).toEqual('foo');
done(); // <-- test if done
}, 800);
});
错误
这在控制台中显示
'expect' was used when there was no current spec, this could be because an asynchronous test timed out
题
如何在fadeOut
完成时测试事件是否发生?
我正在使用Jasmine v2 +
您可以使用waitsFor
等待条件或在超时后失败:
waitsFor(function() {
return $('.c--error').html() == 'foo';
}, "Error was never set to 'foo'", 800);
对于Jasmine 2.0,您可以模拟相同的行为:
describe("stackoverflow test", function() {
var originalTimeout;
beforeEach(function() {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
});
it("it should have a value or hide continue button", function(done) {
// check cover length on select
$(document).on('change', '#select', function(){ checkLengthSelect.call(this) } );
// force a change event to fire with empty value.
$('#select').val('').change();
var POLL_TIME = 10;
var endTime = new Date().getTime() + 5000;
var checkCondition = function() {
if (new Date().getTime() <= endTime && $('.c--error').html() != 'foo') {
setTimeout(checkCondition, POLL_TIME);
} else {
expect($('.c--error').html()).toEqual('foo');
done();
}
};
checkCondition();
});
afterEach(function() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
});
您需要增加异步超时以防止测试失败。 调整POLL_TIME
或添加到当前日期的金额以更改该行为。 我还应该注意,你当前的代码不会碰到checkLengthSelect
的正确分支,所以测试会失败,我在我的测试中翻转了那个分支上的条件,以确保Jasmine部分按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.