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

时间:2018-03-26 16:55:47

标签: javascript jestjs node-mongodb-native

对于这种方法

content.js

const content = await Content.findOne({ _id: articleId })

我喜欢这样的模仿:

content.test.js

Content.findOne = jest.fn(() => Promise.resolve({ some: 'content' }))

但是如何模拟mongo本机驱动程序使用的find.toArray()方法?

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

2 个答案:

答案 0 :(得分:1)

既然你在嘲笑Content的属性,我会说继续这样做。使Content.find返回一个具有toArray属性的对象,该属性是可调用函数:

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

答案 1 :(得分:0)

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