如何在事件发生后执行测试

How to execute tests after an event

我想测试一些需要 Discord.js 客户端才能成为 "ready" 的功能,但我找不到如何在事件发生后让 Jest 运行 成为我的测试。我尝试在

这样的函数中移动测试
client.on("ready", () => {
  test(...);
})

但是当我 运行 npm test 它检测到 0 个测试。 我还尝试在测试中编写 client.on 函数,但它没有检测到 expect 并且没有检查任何东西就通过了。

test("sample", () => {
  client.on("ready", () => {
    expect(...);
  })
})

我试着查看 docs 但我没有找到任何东西。 有人可以帮我吗?

您可以创建一个解决的承诺,测试等待它

test("sample", async() => {
  const p = new Promise((resolve) => {
     client.on("ready", () => {
       resolve()
     })
  })
  await p
  expect(...);

})

另请参阅如何在测试中work with asynchronous code

通过传递 done 参数,Jest 将等待 done() 被调用。

test("sample", done => {
  client.on("ready", () => {
    expect(...);
    done();
  })
})