How to test asyn functions with chai assert

From Chai.js Assertions, Adonis only has Chai Assert.

How are you supposed to test async functions asserts without a lot of boilerplate?

Blog demo has this snippet:

 try {
    await Post.findOrFail(post.id)
    assert.isTrue(false)
  } catch (e) {}

The problem is that the assertion doesn’t fail since it is also caught in the catch block…

The documentation has this example:

  try {
    await badOperation()
  } catch ({ message }) {
    assert.equal(message, 'Some error message')
  }

But if the operation works, it will run without any failures and the bug will go missed.

An alternative:

 try {
    await Post.findOrFail(post.id)
  } catch (e) {
    assert.isTrue(e.constructor.name === 'ExceptionHandler')
  }
  assert.isTrue(false)

But that’s an extra four lines of code compared to using chai expect. And errors caused by this extra boilerplate are harder to catch… most of my incorrect tests were passing when I followed the first example.

@virk I understand the intention with only having chai assert, but how do you handle this problem when testing?

1 Like

Hey @alidcastano! :wave:

I don’t understand your issue here. If there’s no exception thrown the test will be false since we are doing an impossible assertion (assert.isTrue(false)). This lets us test that we have no post in the database.

Yes but say the function doesn’t fail (not working as expected) then the fail assertion will be thrown, but not reported because it is caught in the catch block.

For example, this test passes:

test('test', ({ assert }) => {
  try {
    assert.isTrue(false)
  } catch (e) {}
})

And if you expected it to fail, it’d be a missed bug.

1 Like

This is where you plan your assertions. More in docs here https://adonisjs.com/docs/4.1/testing#_assertions

Let’s say you plan for 1 assertion

assert.plan(1)

and if no assertions have been made, then it fail the tests, saying I was expecting an assertion to be made

3 Likes

Ah ok I was looking at 4.0 docs, didn’t know 4.1 was up. Thanks Virk