首页 > 解决方案 > mssql 连接和查询的笑话

问题描述

无法获得以下模拟测试工作,有人可以帮忙吗?

以下是要测试的源代码:

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";
  }
}

以下是测试:

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("");
    }
  });
});

我需要模拟 mssql 连接和查询并返回一些东西,而不是抛出错误,但我总是抛出错误,如下所示:

expect(received).toBe(expected)  

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

看不懂这个TypeError,查了@types下的mssql,请求类型确实包含查询函数:public query(command: string): Promise<IResult>;

标签: node.jstypescriptjestjsmocking

解决方案


推荐阅读