jhnns / rewire

Easy monkey-patching for node.js unit tests
MIT License
3.08k stars 128 forks source link

Unable to set const variables on imported file #137

Open gazzer82 opened 6 years ago

gazzer82 commented 6 years ago

Trying to write a unit test for an imported function using Chai and rewire and am struggling to be able to override some const set in that file.

So here's my test file.

import 'babel-polyfill';
const chai = require('chai');
const rewire = require('rewire');
const expect = chai.expect;
const nock = require('nock');

const FAKE_KEY = '12345678';

let main = rewire('../handlers/reports/po');

main.__set__('CURRENCY_BIAS', 1.2);
main.__set__('CURRENCY_API_KEY', FAKE_KEY);

const USDJSON = require('./json/currency_usd');
const EURJSON = require('./json/currency_eur');

describe('Test PO Report Generation and Sending', () => {
  describe('Test the Currency Conversion functions', () => {
    // Manually set the currency Bias so we can test
    // Get function we are going to test
    const getAverageCurrency = main.__get__('getAverageCurrency');
    it('Should return a USD rate of ', async() => {
      nock('http://www.quandl.com')
        .get(`/api/v3/datasets/FRED/DEXUSUK/data.json?limit=14&api_key=${FAKE_KEY}`)
        .reply(200, {
          text: USDJSON,
        });
      const USDRATE = await getAverageCurrency('USD');
      expect(USDRATE).to.equal(1.4081714285714286);
    });
  });
});

Importing the file, and then setting some new values, then accessing the function I need to test via rewire get as it's not exported.

Problem is the const values I'm trying to change don't get changed when I call the function.

Here is them being declared in the global scope of the imported file, and the function I am calling which uses them:

require('dotenv').config();

const USDURL = 'http://www.quandl.com/api/v3/datasets/FRED/DEXUSUK/data.json?limit=14&api_key=';
const EURURL = 'http://www.quandl.com/api/v3/datasets/ECB/EURGBP/data.json?limit=14&api_key=';

const request = require('superagent');
const XLSX = require('xlsx');
const moment = require('moment');

const R2APIURL = process.env.R2_API_URL;
const R2APIKEY = process.env.R2_API_KEY;
const CURRENCY_API_KEY = process.env.CURRENCY_API_KEY;
const CURRENCY_BIAS = parseFloat(process.env.CURRENCY_BIAS);
async function getAverageCurrency(symbol) {
  let url;
  let rate;
  try {
    if(symbol === 'USD') {
      url = `${USDURL}${CURRENCY_API_KEY}`;
    }
    else {
      url = `${EURURL}${CURRENCY_API_KEY}`;
    }
    const res = await request
      .get(url);
    const rates = JSON.parse(res.text);
    rate = (rates.dataset_data.data.reduce((storage, currData) => {
      return storage + parseFloat(currData[1]);
    }, 0.0) / 14);
    return rate;
  }
  catch (err) {
    logger.error(err);
    throw new Error('Error fetching current currency rates');
  }
}

Not really sure what's going on here. I have also set them to hard-coded values rather than environmental variables, but that doesn't seem to make any difference.

Any help most appreciated!

Thanks

Gareth

visoft commented 5 years ago

What test runner are you using? I found you can't override const with Rewire in Jest. Change your constants to let and see if that works. Also see https://github.com/jhnns/rewire/issues/144 and https://github.com/facebook/jest/issues/6803

codejockie commented 4 years ago

Variables declared with const cannot be overridden. You have to use var or let if you must rewire your variables.