DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

Where to place the done() call in Jest unit tests on a middleware that logs the request body to the db?

I have asked thsi question:

I am making my own custom middleware that logs the http body to the database

logger.js

const connect = require('connect')
module.exports = function(db_con){
  const app = connect();
  app.use((req,res,next)=>{
     const sql = `INSERT INTO requests VALUES (:method,:url) returning id`;
     const stmt  = db.prepare(initialInsert);

     const insert_result = initialInsertStmt.run({method:req.method,'url':req.url            });
     req.id = insert_result.lastInsertRowid;

I am in progress of making my own middleware that logs the http request body into DB. But I have trouble on testing it because I do not knwo where to place the jest's done function.

Any idea on that?

Happy Jesus Resurection (Καλή Ανάσταση for Greek Orthodox)

Top comments (1)

Collapse
 
alisinayousofi profile image
Ali Sina Yousofi

In Jest unit tests, the done() function is typically used to signal the end of an asynchronous test. If you are testing a middleware that logs the request body to the database, you should place the done() function call after the middleware has completed its execution and any asynchronous operations have been resolved.

example:

test("middleware logs request body to database", done => {
const mockReq = { body: { foo: "bar" } };
const mockRes = {};
const mockNext = jest.fn();

const db = // mock database implementation

const middleware = (req, res, next) => {
// log request body to database
db.log(req.body)
.then(() => {
// call the next middleware or handler
next();
})
.catch(err => {
// handle any errors
next(err);
});
};

middleware(mockReq, mockRes, mockNext);

// assert that the database was updated with the correct data
db.getData().then(data => {
expect(data).toEqual({ foo: "bar" });
done(); // call done() to signal the end of the test
});
});