Javascript 如何模拟已模拟的find()的toArray()?

Javascript 如何模拟已模拟的find()的toArray()?,javascript,jestjs,node-mongodb-native,Javascript,Jestjs,Node Mongodb Native,对于这种方法 content.js const content = await Content.findOne({ _id: articleId }) Content.findOne = jest.fn(() => Promise.resolve({ some: 'content' })) 我模仿的方式如下: content.test.js const content = await Content.findOne({ _id: articleId }) Content.findOn

对于这种方法

content.js

const content = await Content.findOne({ _id: articleId })
Content.findOne = jest.fn(() => Promise.resolve({ some: 'content' }))
我模仿的方式如下:

content.test.js

const content = await Content.findOne({ _id: articleId })
Content.findOne = jest.fn(() => Promise.resolve({ some: 'content' }))
但是如何模拟mongo本机驱动程序使用的
find.toArray()
方法呢

const posts = await Content.find({ category: 'foo' }).toArray()

既然您在模拟
内容的属性
,我想说的是继续这样做。生成
Content.find
返回具有
toArray
属性的对象,该属性是可调用函数:

Content.find = jest.fn(() => ({ toArray: _ => [
  { some: 'content' },
  { some: 'content' }
] }));

您不应该调用mongo的本机驱动程序,因为您没有测试mongo驱动程序(对吗?)。
您应该做的是模拟mongo的本机驱动程序。

我确实得到了错误
内容。查找(…)。toArray不是函数
@user3142695抱歉,我编辑了它。我意识到你在这里不需要承诺。如果有多个函数,比如
Content.find({category:'category}).sort({foo:-1}).limit(1).toArray()
返回这个.collection.find(filter).limit(limit).skip(skip).toArray()
我有这样的场景,我需要模拟limit,skip,排列方法并监视它们以检查是否已调用()。我可以像你建议的那样去模仿,但是如何去发现它们呢?我之所以这么说是因为模仿驱动程序和你使用的方法要容易得多,而不是模仿驱动程序使用的所有东西。这也是正确的测试方法。想一想,如果你升级了你的驱动程序,他们改变了他们的内部逻辑会发生什么。你必须改变你的测试,因为它们改变了内在逻辑。如果他们更改
集合.find().toArray()
模式,那么这就没有意义了,不仅仅是那些被破坏的测试。