title: jest.setTimeout.Error: Mocking Express middleware with Jest and Supertest
body: <p>I would like to mock the auth middleware function to always just call <code>next()</code>. To try and acheive this, I added the following to the beginning of my test file before the auth middleware function is added to the app in <code>app.js</code>.</p>
  <pre><code>jest.mock('../../middleware/auth.js', () =&gt;
    // ensure func is mocked before being attached to the app instance
    jest.fn((req, res, next) =&gt; next()) // seems to only work for first request that hits this middleware
  ); // Mock authentication
  </code></pre>
  <p>I then added some debugs in the auth middleware but did not hit them for any of the tests.</p>
  <p>Currently I am using the following, when the <code>beforeEach()</code> function is not commented out the tests all pass:</p>
  <p>role.test.js</p>
  <pre><code>jest.mock('../../middleware/auth.js', () =&gt;
    // ensure func is mocked before being attached to the app instance
    jest.fn((req, res, next) =&gt; next()) // seems to only work for first request that hits this middleware
  ); // Mock authentication
  
  const request = require('supertest');
  const app = require('../../app.js');
  const Role = require('../../../db/models/index.js').Role;
  // const auth = require('../../middleware/auth.js');
  /**
   * Test role API routes
   */
  describe('role-router', () =&gt; {
    let res;
    const token = 'valid-token';
    const baseUrl = '/private/api/roles';
  
    // Without the `beforeEach()` only the first request sent using supertest will use the mocked functionality
    // With the `beforeEach()` everything functions as expected, but why?
    // beforeEach(() =&gt; {
    //   auth.mockImplementation((req, res, next) =&gt; next());
    // });
  
    describe(`Create new role | post ${baseUrl}`, () =&gt; {
      describe('When successful', () =&gt; {
        beforeAll(async () =&gt; {
          // this will use the proper mocked functionality
          res = await request(app)
            .post(baseUrl)
            .set('Authorization', token)
            .send({
              roleName: 'Secret Agent',
              roleDesc: &quot;World's best secret agent&quot;,
              ...
            });
        });
  
        // passes
        it('Should return 201', () =&gt; {
          expect(res.status).toBe(201);
        });
      }); // When successful
    }); // Create new role
  
    describe(`Delete role by id | delete ${baseUrl}/:id`, () =&gt; {
      describe('When successful', () =&gt; {
        beforeAll(async () =&gt; {
          const role = await Role.create({
            roleName: 'Secret Agent',
            roleDesc: &quot;World's best secret agent&quot;,
            ...
          });
          
          // fails does not get response, res remains the same as res from previous test
          res = await request(app)
            .delete(`${baseUrl}/${role.id}`)
            .set('Authorization', token)
            .send();
        });
  
        // fails with 201
        it('Should return 204', () =&gt; {
          expect(res.status).toBe(204);
        });
      }); // When successful
    }); // Delete role
  }); 
  </code></pre>
  <p>Error received:</p>
  <pre><code> ● role-router › Delete role by id | delete /private/api/roles/:id › When successful › Should return 204
  
      Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.
  
        at mapper (node_modules/jest-jasmine2/build/queueRunner.js:29:45)
  </code></pre>
  <p>app.js</p>
  <pre><code>// Dependencies
  const express = require('express');
  const auth = require('./middleware/auth.js');
  ...
  
  /**
   * Express application
   */
  const app = express();
  
  // Middleware
  app.use(express.json());
  ...
  
  // Private routes are secured with jwt authentication middleware
  app.all('/private/*', (req, res, next) =&gt; auth(req, res, next));
  
  // Public routes
  ...
  
  // Private routes
  app.use('/private/api/roles/', require('./components/role/role-router.js'));
  ...
  
  module.exports = app;
  </code></pre>
  <p>Any ideas why this is not working without using the <code>beforeEach()</code> function to mock the middleware functionality before every test? Perhaps I am missing something more serious?</p>