Jest mock of mssql connection and query

Viewed 366

Can't get following mock testing work, can anyone help?

following is the source code to be tested:

import { ConnectionPool, Request, VarChar } from "mssql";

export const handler = async (): Promise<any> => {

  let connectionPool: ConnectionPool;
  let config = {
    server: "",
    port: 1433,
    database: "db",
    user: "user",
    password: "password",
    trustServerCertificate: true
  };

  try {
    connectionPool = new ConnectionPool(config);
    connectionPool.connect();

  } catch (ConnectionError) {

    throw "ConnectionError";
  }

  try {

    let request: Request = connectionPool.request();
    request.input('param1', VarChar, 'param1');
    request.input('param2', VarChar, 'param2');

    let insertQuery = "INSERT INTO TEST_TABLE (column1, column2 ) VALUES (@param1, @param2) ";

    return await request.query(insertQuery);

  } catch (InsertError) {

    throw "InsertError";
  }
}

Following is the testing:

import {ConnectionPool, Request} from "mssql";
import { handler } from './mock';

const mockQuery = jest.fn().mockReturnValue("result");
const mockInput = jest.fn(() => ({ query: mockQuery }));
const mockRequest = jest.fn(() => ({ input: mockInput }));

jest.mock('mssql', () => ({
  ConnectionPool: jest.fn(() => ({
    request: mockRequest
  })) 
}));

describe('test handler', () => {
  it('should succeed', async () => {

    try {
      let res = await handler();
      expect(res).toBe("result");
    } catch (error) {
      expect(error).toBe("");
    }
  });
});

I need to mock the mssql connection and query and return something, not throw an error, but I always got error thrown, like following:

expect(received).toBe(expected)  

 Expected: ""
 Received: [TypeError: request.query is not a function]

Not understand this TypeError, I chhecked mssql under @types, Request type does include query function: public query(command: string): Promise<IResult>;

0 Answers
Related