如何在TypeScript中使用jest mock MongoDB管理类及collection方法
解决方法
你需要先构造符合mongodb Db类型的mock对象,在对象中实现collection方法的mock即可,完整测试用例写法如下:
import { Db, Collection } from 'mongodb'; import DBManager from './dbManager'; describe('db操作测试', () => { it('可正确获取集合实例', async () => { // 1. 定义mock集合对象,可根据测试需要扩展find、insertOne等业务用到的方法 const mockCollection = { find: jest.fn().mockReturnThis(), toArray: jest.fn().mockResolvedValue([{ _id: '1', name: '测试数据' }]), insertOne: jest.fn().mockResolvedValue({ insertedId: 'mock_id' }) } as unknown as Collection; // 2. 定义mock的db实例,实现collection方法 const mockDb = { collection: jest.fn(() => mockCollection) } as unknown as Db; // 3. 初始化实例并mock对应方法 const testCollectionName = 'user'; const dbManager = new DBManager('mongoUrl'); jest.spyOn(dbManager, 'start').mockResolvedValue(); jest.spyOn(dbManager, 'db', 'get').mockReturnValue(mockDb); // 执行业务逻辑 await dbManager.start(); const db = dbManager.db; const collection = db.collection(testCollectionName); // 断言校验逻辑 expect(mockDb.collection).toHaveBeenCalledWith(testCollectionName); expect(collection).toEqual(mockCollection); }) })
如果不需要校验集合内部的方法调用,仅需要通过类型校验,可以简化mockCollection的定义,不需要写具体的方法实现。后续需要测试集合操作的返回结果时,直接修改对应mock方法的返回值即可。
内容的提问来源于stack exchange,提问作者Hulusi
相关产品推荐
相关产品推荐

