title: How to mock a variable inside a Jest test function?
body: <p>I'm testing the Express application with Jest and came across a slight problem - the module uses variable that is initialized before the test execution, here is my <strong>app.js</strong> file:</p>
  
  <pre><code>const app = express();
  const isDev = process.env.NODE_ENV === 'development';
  
  app.get('*', (req, res, next) =&gt; {
    if (isDev) {
      res.status(404).json({ error: 'Wrong URL' });
    } else {
      res.sendFile(path.join(__dirname, '../index.html'));
    }
  });
  
  app.use(errorHandler);
  
  module.exports = app;
  </code></pre>
  
  <p>When I run Jest tests, my <code>process.env.NODE_ENV</code> is equal to <code>test</code>, that's why I can't cover the first <code>if</code> condition, where <code>isDev</code> is <code>true</code>.
  I've tried to reassign <code>process.env.NODE_ENV</code> before the test request - it works, but as <code>isDev</code> variable initialization has been done before test execution, it didn't work.</p>
  
  <p>This is my test:</p>
  
  <pre><code>const request = require('supertest');
  const app = require('../app');
  
  describe('GET /*', () =&gt; {
    const OLD_ENV = process.env;
  
    beforeEach(() =&gt; {
      // Clear JEST cache
      jest.resetModules();
      process.env = { ...OLD_ENV };
      Reflect.deleteProperty(process.env, 'NODE_ENV');
    });
  
    test('Not existing path (development env) - 404 status', async () =&gt; {
      process.env.NODE_ENV = 'development';
  
      const response = await request(app).
        get('/wrongUrl');
      expect(response.status).toBe(404);
  
    });
  
  });
  </code></pre>
  
  <p>How can I mock the <code>isDev</code> variable inside my test?</p>