user3142695
user3142695

Reputation: 17352

How to mock toArray() of mocked find()?

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()

Upvotes: 2

Views: 2335

Answers (2)

Paul
Paul

Reputation: 141877

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' }
] }));

Upvotes: 5

Yftach
Yftach

Reputation: 752

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.

Upvotes: 0

Related Questions