How to mock mongoose schema method in Jest?

Viewed 248

I am trying to test an endpoint which has some middleware 'getFromRequestLean'. I am correctly mocking this but when I add '.User'to the end of the require function, it returns me the error listed below. I have to do it this way as it's a schema method. What am I doing wrong? How do I mock this Schema method correctly?

const User = require('../models/user').User

router.get('/banner', User.getFromRequestLean, function (request, res) {
})

// model user:

module.exports = {
  User: mongoose.model('User', userSchema),
}

This issue is I can mock by doing:

const User = require('../models/user').User
const getFromRequestLean = require('../models/user').getFromRequestLean

jest.mock('../models/User', () => ({
  getFromRequestLean: jest.fn(),
  User: jest.fn()
}))

describe('validate banner endpoint', () => {
  getFromRequestLean.mockImplementation((req, res, next) => {
    req.user = { some hash attributes... }
    next()
  })
})

I am getting Route.get() requires a callback function but got a [object Undefined]

1 Answers

I struggled a lot on a similar case, I ended up using jest.spyOn:

jest.spyOn(require('../models/user'), 'getFromRequestLean')
  .mockImplementation(() => (req, res, next: any) => next({
    // your code here
  })
)
Related