2

For this method

content.js

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

I do the mock like:

content.test.js

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

But how do I mock a find.toArray() method which is used by the mongo native driver?

const posts = await Content.find({ category: 'foo' }).toArray()
user3142695
  • 15,844
  • 47
  • 176
  • 332

2 Answers2

5

Since you are mocking properties of Content, I would say to just continue to do that. Make Content.find return an object with a toArray property that is a callable function:

Content.find = jest.fn(() => ({ toArray: _ => [
  { some: 'content' },
  { some: 'content' }
] }));
Paul
  • 139,544
  • 27
  • 275
  • 264
  • I do get the error `Content.find(...).toArray is not a function` – user3142695 Mar 26 '18 at 17:05
  • @user3142695 Sorry, I edited it. I realized that you don't need a Promise here. – Paul Mar 26 '18 at 17:12
  • What about cases with multiple functions like `Content.find({ category: 'category }).sort({ foo: -1 }).limit(1).toArray()`? – user3142695 Mar 26 '18 at 17:56
  • `return this.collection.find(filter).limit(limit).skip(skip).toArray()` I have a scenario like this , I need to mock limit, skip, toArray methods and spyOn them to check toHaveBeenCalledWith(). I can able to mock as you suggested but how to spy them? – muthu Jan 14 '20 at 06:29
0

You should not be calling mongo's native driver as you are not testing the mongo driver (right?). What you should do is mock mongo's native driver.

Yftach
  • 712
  • 5
  • 15
  • The reason i'm saying this is its much easier to mock the driver and the methods you are using of that driver and not to mock all the things the driver is using. It is also the right approach to testing. Think for a second what happens if you upgrade your driver and they change their inner logic. You would have to change your tests just because they changed inner logic. that doesnt make sense – Yftach Mar 26 '18 at 17:14
  • If they change the `collection.find().toArray()` pattern, then it won't just the tests that are broken. – emragins Apr 27 '21 at 18:38