0
votes

I am trying to test a (to me) complex piece of code that I would like to just return dummy data so I can do assertions on how it is handled. Here is the code:

const { sql, dbConnPoolPromise } = require('../database/db.js');
router.get('/', async (req, res) => {
    try {
        const pool = await dbConnPoolPromise
        const result = await pool.request()
            .query(SQL_SELECT_ALL);
        res.status(200);
        res.json(result.recordset[0]);
    } catch (err) {
        res.status(500);
        res.send("ERROR, General Get" + err.message);
    }
});

I want to replace the const result with a set piece of dummy data, thus mocking the response a SQL server might give. I cannot figure out how to do this. I am currently using Jest as my testing suite and was hoping to use spyOn or Jest.fn() to replace it but that only works on functions. Is there a way in jest to replace variables? I cannot replace the entire router.get as I am testing that res.status(200) (amongst others) is being sent correctly to the client, I only want to replace the value of the variable.

If required the contents of dbConnPoolPromise are:

let sql = require('mssql');
const config = require('config');
let dbConnPoolPromise = new sql.ConnectionPool(config.get('connection'))
        .connect()
        .then(pool => {
        return pool
        })
        .catch(err => console.log('Database Connection Failed - error: ', err))
module.exports = {
    sql, dbConnPoolPromise, buildSelect
};
1

1 Answers

0
votes

You can access your query from a service wrapper, something like.

export function async getAllItems() {
  const pool = await dbConnPoolPromise
  return await pool.request().query(SQL_SELECT_ALL)
}

Then you can use jest's manual mocks functionality https://jestjs.io/docs/en/manual-mocks to mock out the response of getAllItems.

As a broader comment, this is usually why we have patterns to access DB from a repository or service rather than directly hitting it from a controller or route like this. Once you wrap it in a service, it makes it so much easier for you to mock it out during a test.