开玩笑,我如何模拟 mongodb.Db 的实例进行单元测试?

时间:2021-06-10 02:20:09

标签: mongodb mongoose jestjs mocking ts-jest

我使用的是 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 实例,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以创建一个模拟的 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');
  });
});