如何使用 Jest 模拟 SQL 服务器连接池?

How to mock SQL Server connection pool using Jest?

我正在尝试为使用 mssql.

的函数编写一个有趣的单元测试
import * as sql from "mssql";

let pool: sql.ConnectionPool = null;

export async function handler() {
  if (pool === null) {
    try {
      pool = new sql.ConnectionPool("");
      await pool
        .request()
        .input("SomeInput", sql.NVarChar(255), "input")
        .execute("SomeStoredProcedure");
    } catch (err) {
      console.error(err);
    }
  }
}

模拟 sql 方法并断言它们已被调用的最简单方法是什么?

import { handler } from "../src/main";

describe("test handler", () => {
  it("should succeed", async () => {
    const requestFn = jest.fn();
    const executeFn = jest.fn();
    const inputFn = jest.fn();
    
    // Mock mssql connection pool with above functions
    // *????????*
    
    await handler();
    
    // Expect the functions have been called
    expect(requestFn).toHaveBeenCalled();
    expect(executeFn).toHaveBeenCalled();
    expect(inputFn).toHaveBeenCalled();
  });
});

Sandbox

您需要模拟链中每个函数的 return 值。您可以使用 jest.fn().mockImplementation(implementation)

扩展你的例子来使用这个给我们以下

import { handler } from "../src/main";

let pool;

describe("test handler", () => {
  it("should succeed", async () => {
    const requestFn = jest.fn();
    const executeFn = jest.fn();
    const inputFn = jest.fn();
    
    pool = {
      request: requestFn,
      execute: executeFn,
      inputFn: inputFn,
    };

    requestFn.mockImplementation(() => pool);
    executeFn.mockImplementation(() => pool);
    inputFn.mockImplementation(() => pool);

    await handler();
    
    // Expect the functions have been called
    expect(requestFn).toHaveBeenCalled();
    expect(executeFn).toHaveBeenCalled();
    expect(inputFn).toHaveBeenCalled();
  });
});

您可以使用 jest ES6 Class Mocks 模拟 mssql 包。您可以通过以下方式实现:

const mockExecute = jest.fn();
const mockInput = jest.fn(() => ({ execute: mockExecute }));
const mockRequest = jest.fn(() => ({ input: mockInput }));

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

在终端中查看 Stackblitz 项目和 运行 jest。您应该看到测试正在通过。