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