How to execute tests after an event

87
April 29, 2018, at 7:54 PM

I want to test some functions that require a Discord.js Client to be "ready", but I don't find how to make Jest run my tests after an event. I tried moving the tests in a function like

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

but when I run npm test it detects 0 tests. I also tried to write the client.on function inside the tests but it doesn't detect the expect and passes without checking anything.

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

I tried looking at the docs but I didn't find anything. Can somebody help me?

Answer 1

You could create a promise that resolves and the test waits for it

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

Also have a look on how to work with asynchronous code in tests

Answer 2

By passing the done argument Jest will wait until done() is called.

test("sample", done => {
  client.on("ready", () => {
    expect(...);
    done();
  })
})
READ ALSO
Detect filetype and assign file extension based on that: Node.js

Detect filetype and assign file extension based on that: Node.js

I want to detect the filetype of the originalname and based on that assign the extension to my file upload

117
Nodejs res.render function not updating html page

Nodejs res.render function not updating html page

I have a nodejs application that sends values to html page using resrender function

77
how to point from Local host to my ip address, DNS with nodejs

how to point from Local host to my ip address, DNS with nodejs

I pulled a github repository from; https://githubcom/Shapeshift-Public/ShapeShift-Skeleton its a nodejs app

114