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

使用Jest与Supertest测试本地MongoDB时出现超时错误求助

Jest连接本地MongoDB测试超时问题排查与解决

问题描述

我在学习使用Jest编写测试,已将Jest连接至测试数据库,但无论设置多长超时时间,Jest仍会抛出超时错误。测试使用Jest+Supertest验证用户注册接口(POST /signup),该接口负责创建新用户并返回token。测试在使用云托管MongoDB时正常运行,但切换至本地MongoDB时,测试会超时失败。

测试代码

const request = require('supertest');
const mongoose = require('mongoose');
const app = require('../app');
const User = require('../models/userModel');

const url = 'mongodb+srv://zenerbogyah7:test1234@cluster0.utpa6al.mongodb.net/';

beforeAll(async () => {
  await mongoose.connect(url, { useNewUrlParser: true });
});

afterAll(async () => {
  await User.deleteMany({});
  await mongoose.connection.close();
});

describe('POST /signup', () => {
  test('should create a new user and return a token', async () => {
    const userData = {
      name: 'John Doe',
      email: 'johndoe@test.com',
      password: 'testpassword',
      passwordConfirm: 'testpassword',
    };

    const response = await request(app).post('/api/signup').send(userData);
    expect(response.status).toBe(201);
    expect(response.body).toHaveProperty('token');
  }, 10000);
});

错误信息

thrown: "Exceeded timeout of 10000 ms for a test. Add a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."

解决方案

  • 修正本地MongoDB连接配置
    确保使用本地MongoDB的正确连接URL,比如本地默认实例的URL为mongodb://localhost:27017/your-test-database(替换为你的测试库名),不要继续使用云数据库的URL。同时确认本地MongoDB服务已启动,端口27017未被其他进程占用。

  • 完善MongoDB连接参数与错误捕获
    旧版本Mongoose需要添加useUnifiedTopology: true参数确保连接稳定,同时在连接逻辑中加入错误捕获,避免连接失败导致测试无限等待:

    beforeAll(async () => {
      try {
        await mongoose.connect('mongodb://localhost:27017/test-db', {
          useNewUrlParser: true,
          useUnifiedTopology: true
        });
      } catch (err) {
        console.error('本地MongoDB连接失败:', err.message);
        process.exit(1); // 连接失败直接终止测试
      }
    });
    
  • 优化测试后清理逻辑
    使用dropDatabase()替代deleteMany({}),更高效地清空测试数据,避免因清理操作耗时过长导致超时:

    afterAll(async () => {
      await mongoose.connection.dropDatabase();
      await mongoose.connection.close();
    });
    
  • 排查接口响应阻塞
    在测试中添加日志,确认请求是否真的发送到接口并得到响应:

    const response = await request(app).post('/api/signup').send(userData);
    console.log('接口响应:', response.status, response.body);
    

    检查本地环境下用户注册接口的逻辑,比如密码加密、数据库写入等步骤是否存在性能瓶颈,导致响应缓慢。

  • 调整Jest全局超时
    若单个测试的超时设置仍不够,可以在Jest配置文件(jest.config.js)中设置全局超时时间:

    module.exports = {
      testTimeout: 20000, // 全局设置20秒超时
    };
    

内容的提问来源于stack exchange,提问作者Clement Owireku-Bogyah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:08:14