javascript - 在 addEventListener() 上的 Ava 测试 setTimeout()
问题描述
我有我想测试的这个功能ava
和browser-env
function foo () {
setTimeout(() => {
const event = new CustomEvent('pushcommand', { detail: 'foo', bubbles: true })
document.getElementById('command-history').dispatchEvent(event)
}, 1)
}
我的测试代码是:
import test from 'ava'
import foo from 'foo.js'
test('foo', t => {
document.body.innerHTML = '<ul id="command-history"></ul>'
document.getElementById('command-history').addEventListener('pushcommand', event => {
t.is(event.detail, 'foo')
})
foo()
})
但我在ava
:中得到错误Error: Test finished without running any assertions
。来自事件侦听器的代码被执行,只是 ava 在退出测试之前没有到达它。
任何人都知道如何解决这个问题?
我试过了test.serial
,,无济于事。请帮忙。async await
t.end()
解决方案
异步等待可能很棘手。测试可能在调用异步回调之前结束。因为没有返回承诺(异步),所以 ava 不知道要等到测试完成。像这样的东西应该有助于与 ava 沟通,等待承诺完成
import test from 'ava'
import foo from 'foo.js'
function foo () {
setTimeout(() => {
const event = new CustomEvent('pushcommand', { detail: 'foo', bubbles: true })
document.getElementById('command-history').dispatchEvent(event)
}, 1)
}
test('foo', async (t) => {
document.body.innerHTML = '<ul id="command-history"></ul>'
await new Promise((resolve, reject) => {
window.addEventListener('error', reject)
document.getElementById('command-history').addEventListener('pushcommand', event => {
t.is(event.detail, 'foo')
resolve()
})
foo()
})
})
推荐阅读
- google-cloud-platform - 如何在不提交服务密钥的情况下使用服务密钥向 gcloud SDK 进行身份验证?
- python - 当输入是列表时,在 seaborn 中对箱线图/小提琴图进行分组
- pyspark - DATABRICKS SparkException:在 awaitResult 中引发异常 - 无法显示数据帧
- primefaces - PrimeFaces confirmDialog 更改语言后不会显示
- apache-kafka - KafkaCat 和 Docker:消息太大
- javascript - Chart.js 雷达工具提示显示太多值
- apache-spark - Spark - 30 分钟通用窗口化
- python - 如何获得熊猫时间范围的平均值
- pandas - 使用日期合并/连接非唯一多索引
- java - Spring Boot,JPA / Hibernate:如何一次执行两个原始 SELECT 查询?