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

如何用Jest模拟NodeJS+TypeScript静态方法及测试insert方法?

Jest测试Node.js+TypeScript Repository层实操指南

一、模拟MongoConfig获取Collection对象

要在MyRepository._getCollection中拦截MongoConfig.getDatabase().collection()调用并返回模拟集合,按以下步骤操作:

  1. Mock MongoConfig模块
    直接用Jest的jest.mock模拟你的自定义MongoConfig类所在模块:

    // 替换为你的MongoConfig实际路径
    jest.mock('../src/config/mongo.config');
    
  2. 构建模拟Collection
    创建带追踪方法的模拟集合,用jest.fn()记录调用行为:

    const mockCollection = {
      insertOne: jest.fn().mockResolvedValue({ insertedId: 'mock-doc-id' })
    };
    
  3. 链式模拟数据库调用
    让getDatabase()返回的对象包含collection方法,该方法直接返回我们的模拟集合:

    (MongoConfig.getDatabase as jest.Mock).mockReturnValue({
      collection: jest.fn().mockReturnValue(mockCollection)
    });
    
  4. 验证_getCollection行为
    实例化MyRepository后调用_getCollection,验证链式调用是否符合预期:

    const repo = new MyRepository();
    repo._getCollection(); // 若方法为private,可改为protected或通过内部逻辑触发调用
    
    expect(MongoConfig.getDatabase).toHaveBeenCalled();
    expect(MongoConfig.getDatabase().collection).toHaveBeenCalledWith('目标集合名称');
    

二、insert方法的测试要点

测试insert方法不只是验证insertOne被调用,还需要覆盖核心场景:

1. 基础调用验证

确认insertOne传入了正确的数据:

test('insert方法应调用insertOne并传入正确数据', async () => {
  const testData = { username: 'test-user', email: 'test@example.com' };
  const repo = new MyRepository();
  
  await repo.insert(testData);
  
  expect(mockCollection.insertOne).toHaveBeenCalledWith(testData);
});

2. 返回值验证

如果insert方法会返回插入结果(如文档ID),需验证返回值是否符合预期:

test('insert方法应返回插入的文档ID', async () => {
  const testData = { username: 'test-user' };
  const repo = new MyRepository();
  
  const result = await repo.insert(testData);
  
  expect(result).toEqual({ insertedId: 'mock-doc-id' });
});

3. 错误处理验证(可选)

若insert方法包含错误捕获逻辑,需模拟异常场景验证处理逻辑:

test('insert方法应正确处理数据库插入错误', async () => {
  const testData = { username: 'test-user' };
  const mockError = new Error('数据库插入失败');
  mockCollection.insertOne.mockRejectedValue(mockError);
  
  const repo = new MyRepository();
  
  await expect(repo.insert(testData)).rejects.toThrow(mockError);
});

内容的提问来源于stack exchange,提问作者Jignesh M. Khatri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:42:17