How to write unit test for cassandra execute query in nodejs using jest framework

Viewed 806

I'm trying to write a unit test case against my code which fetches campaigns/data from the Cassandra DB. I'm using the Jest framework for my unit testing.

const db = require('../../db/client');
getCampaigns(req: express.Request, res: express.Response) {
      db.execute('select * from campaign_definitions', (err: any, 
result: any) => {
        if (err) {
          logger.error(`${err.status || 500} - ${err.message} - 
${req.originalUrl} - ${req.method} - ${req.ip}`);
          return res.status(500).send(err);
        }
        res.send(result.rows);
      });
    }

I don't know how to make the mock for 'db.execute' using jest. I appreciate your help, thanks

1 Answers

You can mock db.execute to do nothing and use the mock to get the arguments passed to it.

The arguments are the query and the callback, so you just need to test that the query is correct and the callback works as expected.

Here is a simplified working example to get you started:

import * as express from 'express';
const db = require('../../db/client');

function getCampaigns(req: express.Request, res: express.Response) {
  db.execute('select * from campaign_definitions', (err: any, result: any) => {
    res.send(result.rows);
  });
}

test('getCampaigns', () => {
  const res: any = { send: jest.fn() };
  const mock = jest.spyOn(db, 'execute');  // spy on db.execute...
  mock.mockImplementation(() => {});  // <= ...and mock the implementation

  getCampaigns({} as any, res);

  const args = db.execute.mock.calls[0];  // <= get the args passed to db.execute
  const query = args[0];
  const callback = args[1];
  callback(null, { rows: 'the rows' });  // <= call the callback

  expect(query).toBe('select * from campaign_definitions');  // Success!
  expect(res.send).toHaveBeenCalledWith('the rows');  // Success!
})
Related