Search code examples
javascriptnockdotenv

How to make Dotenv and Nock work together?


Currently in one of my apps i am using nock to mock my api request.Unfortunately in another test file of same project, i used dotenv.If i use dotenv my nock is not mocking the url, it is using the original api request. Any suggestions or help is appreciated. My test file

'use strict';

const assert = require('assert');
const nock = require('nock');

describe('example', () => {
  afterEach(async() => {
    nock.cleanAll();
  });

  describe("checktest", () => {

    it("checksomeupdate", async() => {
      nock('http://example.com')
        .get('/demend-point')
        .reply(200, {
          x: 1
        })

      const result = await demoCallToMainFileMetho();
      const [a, b] = result || []; // response array [1,2,3]
      assert.ok(a.includes('1'));
    });
  });
});

My other file in test dir

require('dotenv').config();
.....some code

Solution

  • My issue is fixed. Solution: I had to remove dotenv package from my script.Where ever i needed that i had to replace with

    process.env = Object.assign(process.env, 
        { DEMO_VARIABLE_ONE: 'false' },
        { DEMO_VARIABLE_ONE_URL: 'value' },
        { DEMO_VARIABLE_TWO: 'value' }
    );