javascript - 如何等待执行异步函数的 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。
- 我不相信第一个是合适的,因为我不是想监视命名函数,这些是匿名函数处理程序
- 第二个链接中的选项对于代码直接返回承诺的情况看起来很有用
- 第三个只有在我有一个特定选择器的事件处理程序时才有用,它只调用一个处理程序。这不是我的代码库的情况,正如前面的“选择器”和“选择器2”所证明的那样。改变这一点需要大量的工作,所以我不愿意在没有先探索所有其他选择的情况下这样做。
我的第一个问题是,我是否正确理解了异步概念,或者我是否遗漏了一些可以让我的任务更轻松的基础知识?其次,有没有办法“等待”异步事件处理程序?
解决方案
推荐阅读
- unix - 在我“npm install -g”之后,我无法使用已安装包中的 CLI 命令
- reactjs - Uncaught TypeError: _this.props.startAddComponent is not a function 尝试使用 mapDispatchToProps
- c# - 我想在通用 TEntity 类上创建一个反射并枚举其属性以急切地获取它们
- azure - 如何加载数组
从存储在 Amazon S3 中的镶木地板文件到 Azure 数据仓库的数据类型? - python - Python 代码跳过识别数字
- android - 如何使用 DatePickerDialog 设置开始和结束日期?
- spring-boot - SpringBoot Junit 测试主要方法
- android - 如何在 Flutter 上的两个地理点之间绘制路线?
- python - 如何修复“列表索引必须是整数或切片,而不是列表”错误?
- ios - 可以单独设置我的 AVFoundation 相机吗?