title: Mock Middleware supplied to req in an Express Route using Jest
body: <p>I have the following Express route: </p>
  
  <pre><code>app.route(`api/project`).post((req, res) =&gt; createProject(req, res))
  </code></pre>
  
  <p>In previous code, I had created middleware to attach Mongoose to the <code>req</code> object, so it can be called with <code>req.mongoose</code> inside of <code>createProject</code>. </p>
  
  <p>The problem is that I don't know how to mock <code>req.mongoose</code> when used in Unit Tests.</p>
  
  <p>I tried creating a Manual Mock of <code>createProject</code> (below) that called the real <code>createProject</code> with <code>req.mongoose</code> being set to the stub, but this caused a StackOverflow error.</p>
  
  <pre><code>// __mocks__/createProject.js
  
  const { MongoMemoryServer } = require('mongodb-memory-server')
  const realCreateProject = require('../createProject')
  const mongoose = require('mongoose')
  
  const createProject = async (req, res) =&gt; {
    const mongoServer = new MongoMemoryServer()
    const mongoUri = await mongoServer.getConnectionString()
  
    const options = { useNewUrlParser: true }
  
    await mongoose.connect(mongoUri, options, err =&gt; {
      if (err) console.error(`ERROR: beforeAll - ${err}`)
    })
  
    req.mongoose = mongoose
  
    realCreateProject(req, res)
  }
  </code></pre>
  
  <p>So, how would you mock out the <code>req</code> object in a route before it gets passed down the line?</p>