首页 > 解决方案 > 如何等待执行异步函数的 jQuery 事件处理程序

问题描述

我最近不得不在我的代码中添加一些异步函数,这导致了我的笑话测试中的问题。

我有许多看起来像这样的 jQuery 事件处理程序:

// production code
jQuery(document).on('change', 'selector', (function () {
    // ...
    function(); // loads a hard-coded bit of JSON or loads from localStorage
    // ...
}));
// jest code for checking the side effects
/// @Note: 'selector2' below is not the same as 'selector' above, but the event handler 
/// will be called due to the event propagation
$('selector2').trigger('click');
expect($('selector2').prop('checked')).toBe(true); // checkbox should become checked
expect(JSON.parse(localStorage.getItem('key'))).toBe(true); // localStorage should change

现在看起来像这样:

// production code
$(document).on('change', 'selector', (async function () {
    // ...
    await functionButNowItsAsync(); // uses fetch() to load the JSON or loads from localStorage
    // ...
}));
// jest code for checking the side effects
/// @Note: 'selector2' below is not the same as 'selector' above, but the event handler 
/// will be called due to the event propagation
$('selector2').trigger('click');
/* The following no longer pass because the promise is not resolved */
expect($('selector2').prop('checked')).toBe(true); // checkbox should become checked
expect(JSON.parse(localStorage.getItem('key'))).toBe(true); // localStorage should change

我的研究让我想到了jest.spyOn这篇博文和jQuery.triggerHandler

我的第一个问题是,我是否正确理解了异步概念,或者我是否遗漏了一些可以让我的任务更轻松的基础知识?其次,有没有办法“等待”异步事件处理程序?

标签: javascriptjestjs

解决方案


推荐阅读