0

Is there are way to force mocha to require a return value from tests? When testing Promises i do it like:

it("some test", () => {
  return someFunctionThatReturnsAPromise()
    .then(result => {
      assert.ok(result)
      // ...
    })
})

and everything passes/fails as it should whether or not the Promise is resolved or rejected. But if I forget to the "return" (which I do A LOT), then the test passes even if the Promise is rejected.

NOTE: I'm using npm-current mocha with chai-assert.

Phuo
  • 221
  • 2
  • 5

2 Answers2

0

Convert your test into an async test:

it("some test", async () => {
  asset.ok(await someFunctionThatReturnsAPromise())
})

programmerRaj
  • 1,810
  • 2
  • 9
  • 19
  • Yea I thought of that, and that is how my tests were originally written, but the non-async/await wait seems a lot cleaner. I'd rather not riddle all tests with async/awaits all over the place. – Phuo Sep 01 '21 at 12:04
  • If you don't want to use async tests, it will be nearly impossible, and your question is very similar to https://stackoverflow.com/questions/9121902/call-an-asynchronous-javascript-function-synchronously. – programmerRaj Sep 01 '21 at 16:30
0

I was able to fix this by setting mocha's asyncOnly option to true (https://mochajs.org/api/mocha).

The unfortunate side effect of this is that ALL tests now must return a Promise (or call done()). That is preferable to me though... So far only one of my test modules (*.test.js) wasn't doing this, but I can just return Promise.resolve() from those for now, until I figure out how to change mocha.asyncOnly on a per-module basis.

Phuo
  • 221
  • 2
  • 5