首页 > 解决方案 > 在 addEventListener() 上的 Ava 测试 setTimeout()

问题描述

我有我想测试的这个功能avabrowser-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 awaitt.end()

标签: javascriptunit-testingsettimeoutjsdomava

解决方案


异步等待可能很棘手。测试可能在调用异步回调之前结束。因为没有返回承诺(异步),所以 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()
  })
})

推荐阅读