我有一个在元素中淡入淡出的简单函数:
代码
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',这可能是因为异步测试超时
问题
我如何测试 fadeOut
完成时是否发生了事件?
我正在使用 Jasmine v2+
最佳答案
Jasmine 1.3
您可以使用 waitsFor
等待条件或超时后失败:
waitsFor(function() {
return $('.c--error').html() == 'foo';
}, "Error was never set to 'foo'", 800);
Jasmine 2.0
对于 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;
});
});
您需要increase the async timeout以防止测试失败。调整 POLL_TIME
或添加到当前日期的数量以更改该行为。我还应该注意,您当前的代码不会命中 checkLengthSelect
的正确分支,因此测试将失败,我在测试中翻转了该分支上的条件,以确保 Jasmine 部分按预期工作.
关于javascript - Jasmine - 等待 fadeOut() 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273289/