1

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() // 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.

0

1 Answer 1

5

Don't use async functions as callbacks - as callbacks are not supposed to return promises; their results will be ignored (and the rejection won't be handled). You should pass the async function to it itself, assuming that Jest knows how to deal with promises.

it('sample test', async () => { const db = await mongodb.MongoClient.connect(config.mongodb.url); expect(db).toBeTruthy(); try { const cursor = await db.collection('my_collection').findOne(); expect(cursor).toBeTruthy(); } finally { // don't `catch` exceptions you want to bubble db.close() } }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.