Wednesday, 12 April 2017

nodejs async/await try/catch jest test passing when it shouldn't

I am learning jest testing using latest ecmascript syntax for my MongoDB back-end code. I am testing right now to see if the test will fail the test if I try to find a document from an empty collection.

The cursor should be null as a result since nothing returns, and that means the cursor is falsey, but the test below still passes even when I tell it to expect truthy and I don't know why:

import config from './config'
const mongodb = require('mongodb')

it('sample test', () => {
  mongodb.MongoClient.connect(config.mongodb.url, async (connectErr, db) => {
    expect(db).toBeTruthy()
    let cursor
    try {
      cursor = await db.collection('my_collection').findOne()
      console.error(cursor)
      // cursor is null, but test still passes below
      expect(cursor).toBeTruthy()
    } catch (findErr) {
      db.close()
    }
  })
})

Also, is this a good test test style? I read somewhere that you shouldn't use try/catch blocks in testing. But that is what you would use to handle async/await errors.



via Dobob

No comments:

Post a Comment