【问题标题】:In jest, how do I mock an instance of mongodb.Db for a unit test?开玩笑地说,我如何模拟 mongodb.Db 的实例以进行单元测试?
【发布时间】:2021-08-27 00:38:31
【问题描述】:

我正在使用 jest 和 mongoose 5.11.11。我有以下功能要进行单元测试...

import { Db } from 'mongodb';
...
export async function createCollectionIfNotExists(
  db: Db,
  collectionName: string,
): Promise<void> {
  if (!(await collectionExists(db, collectionName))) {
    await db.createCollection(collectionName);
  }
}

如何创建“mongodb.Db”类型的模拟对象?我看到了一种使用

监视现有原型方法的方法
jest.spyOn(Db.prototype, 'createCollection').mockImplementation( ...

但我首先必须构建一个 Db 实例,但我不知道该怎么做。

【问题讨论】:

    标签: mongodb mongoose jestjs mocking ts-jest


    【解决方案1】:

    您可以创建一个模拟的db 对象并将其传递给createCollectionIfNotExists 函数。使用类型断言将模拟的db 对象类型指定为Db

    另外,我建议你将collectionExists 函数移动到一个单独的文件中(使用jest.mock('./collectionExists') 方法来模拟)。或者使用像db这样的依赖注入(创建像const collectionExists = jest.fn().mockResolvedValueOnce(false)这样的模拟版本),这样我们就可以轻松地模拟它。

    import { Db } from 'mongodb';
    import { createCollectionIfNotExists } from './';
    
    describe('67913785', () => {
      it('should pass', async () => {
        const mDb = ({ createCollection: jest.fn() } as unknown) as Db;
        await createCollectionIfNotExists(mDb, 'posts');
        expect(mDb.createCollection).toBeCalledWith('posts');
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 2021-04-24
      • 2021-06-16
      • 2021-05-27
      • 1970-01-01
      • 2021-10-22
      • 2020-06-13
      • 2018-06-03
      • 1970-01-01
      相关资源
      最近更新 更多