Home > Net >  Jest - trying to mock db connection that is created in a function using new keyword
Jest - trying to mock db connection that is created in a function using new keyword

Time:11-26

I have the following piece of code that is fetching data from mssql. Is there any way that I can mock away the Connection pool? I want to make the pool.request().execute() call return some mock data. I don't think it's possible and I am currently trying to wrap my head around on how to test this function.

The only solution I could've thought is to use ioc for the connection pool. But before I go ahead and do that I just want to make sure that it's not possible to mock away the connection pool.

Thank you

const fetchData ({args}) => {
  const pool = await new ConnectionPool(conn.getConfig()).connect();
  const result = await pool.request().input(...args).execute('Get_Some_Data');
  pool.close();
  
  // business logic below I want to test
  ...
  ...
}

I have been googling and check the documentation. I don't think it's possible but I would like to confirm.

CodePudding user response:

You can mock constructors using `jest.fn().mockImplementation(). Read more about it in the documentation.

const mockPool = {
    connect: () => mockPool,
    request: () => mockPool,
    input: () => mockPool,
    execute: () => {
        console.log("Called mock execute");
        return [1, 2, 3];
    },
    close: () => console.log("Closed")
}

const ConnectionPool = jest.fn().mockImplementation(() => mockPool)

Example

I am assuming that you are using ConnectionPool from mssql package.

Source Code

const {ConnectionPool} = require("mssql");

const fetchData = async ({args}) => {
    const pool = await new ConnectionPool(conn.getConfig()).connect();
    const result = await pool.request().input(...args).execute('Get_Some_Data');
    pool.close();
    
    // business logic
    return result;
}

Test Script

const {fetchData} = require('./fetch-data');

jest.mock('mssql', ()=> {
    const mockPool = {
        connect: () => mockPool,
        request: () => mockPool,
        input: () => mockPool,
        execute: () => {
            console.log("Called mock execute");
            return [1, 2, 3];
        },
        close: () => console.log("Closed")
    }

    return {
        ConnectionPool: jest.fn().mockImplementation(() => mockPool)
    }
});


it('Mock Connection Pool', async () => {
    const data = await fetchData({args: []});
    expect(data).toStrictEqual([1, 2, 3]);
});

Thanks!

  • Related