小编col*_*suz的帖子

使用 ts-jest/utils 模拟数据库 Jest

我试图模拟数据库调用,但它一直导致db函数返回未定义。

请看一下我的文件。

数据库ts

import * as mysql from "mysql";
import * as util from "util";

{... other functions with named exports}

const getDbConnection = () => {
  const pool = mysql.createPool(DB_CONFIG);
  return {
    query(sql: string) {
      return util.promisify(pool.query).call(pool, sql);
    },
  };
};
export default getDbConnection;
Run Code Online (Sandbox Code Playgroud)

测试名称.spec.ts

import { mocked } from "ts-jest/utils";
import db from "../src/utils/db";

jest.mock("../src/utils/db");
describe("Test Controller", () => {
  afterAll(() => {
    jest.resetAllMocks();
  });

  mocked(db);

  it("should retrieve all", async () => {
    await request(app)
      .get("/data") …
Run Code Online (Sandbox Code Playgroud)

unit-testing node.js jestjs ts-jest

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

jestjs ×1

node.js ×1

ts-jest ×1

unit-testing ×1