Search code examples
javascriptjestjsnode-mongodb-native

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

Solution

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