代码之家  ›  专栏  ›  技术社区  ›  Dave

开玩笑地说,我该如何嘲笑mongodb的一个实例呢。单元测试的Db?

  •  0
  • Dave  · 技术社区  · 5 年前

    我用的是笑话和猫鼬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实例,我不知道如何做到这一点。

    0 回复  |  直到 5 年前
        1
  •  0
  •   Lin Du Correcter    5 年前

    你可以创建一个模拟 db 对象并将其传递给 createCollectionIfNotExists 作用使用类型断言指定模拟的 数据库 对象类型为 Db .

    此外,我建议你把 collectionExists 函数转换为单独的文件(使用 jest.mock('./collectionExists') 方法模拟)。或者像这样使用依赖项注入 数据库 (创建这样的模拟版本 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');
      });
    });