You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest+Typegoose:多测试文件如何使用独立Mongo内存数据库?

问题判断与解决方案

你的怀疑是正确的:当两个测试文件共享同一个mongoose全局实例时,后执行的测试文件会覆盖全局的mongoose连接,导致所有后续的模型创建(包括第一个测试文件里的getModelForClass(User))都会使用最后建立的数据库连接(db2),最终造成两个测试文件的数据互相污染,测试结果不可靠。

解决方案

方案1:为每个测试文件创建独立的Mongoose连接实例

不要使用全局的mongoose.connect,而是用mongoose.createConnection创建专属连接,并且在调用getModelForClass时指定该连接。

修改测试文件中的初始化代码:

import { mongoose, getModelForClass } from "@typegoose/typegoose";
import { User } from "./your-user-class";

// 声明专属连接变量
let testConnection: mongoose.Connection;

beforeAll(async () => {
  if (!process.env.MONGODB_URL_TEST) {
    throw new Error("MONGODB_URL_TEST is not set");
  }
  const uniqueUri = `${process.env.MONGODB_URL_TEST}-${Date.now()}`;

  // 创建独立连接,而非使用全局连接
  testConnection = await mongoose.createConnection(uniqueUri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
});

// 创建模型时指定专属连接
const UserModel = getModelForClass(User, { existingConnection: testConnection });

// 测试结束后关闭当前连接
afterAll(async () => {
  await testConnection.close();
});

方案2:使用Mongoose的createConnection配合Typegoose的setGlobalOptions

如果希望每个测试文件的模型都自动关联到当前连接,可以在初始化时设置全局选项:

import { mongoose, getModelForClass, setGlobalOptions } from "@typegoose/typegoose";
import { User } from "./your-user-class";

let testConnection: mongoose.Connection;

beforeAll(async () => {
  if (!process.env.MONGODB_URL_TEST) {
    throw new Error("MONGODB_URL_TEST is not set");
  }
  const uniqueUri = `${process.env.MONGODB_URL_TEST}-${Date.now()}`;

  testConnection = await mongoose.createConnection(uniqueUri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });

  // 设置全局模型使用当前连接
  setGlobalOptions({ existingConnection: testConnection });
});

// 此时getModelForClass会自动使用上面设置的连接
const UserModel = getModelForClass(User);

afterAll(async () => {
  await testConnection.close();
});

方案3:配置Jest强化测试隔离性

在jest.config.js中开启模块隔离与Mock重置,辅助避免全局状态污染:

module.exports = {
  resetMocks: true,
  isolatedModules: true,
  // 若上述方案仍有问题,可暂时关闭并行测试(会减慢速度)
  // maxWorkers: 1,
};

内容的提问来源于stack exchange,提问作者Tarasko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 07:31:06