jest.mock() - how to mock config.get() from config lib

Viewed 1189

I have two issues

  1. I want to mock the config.get() from config lib to return a value
  2. The mocked return value for config.get should be a date generated from moment

I tried the following but I get an error "is not allowed to reference any out-of-scope variables. Invalid variable access: moment"

Say my function:

function test(configVariable) {
  const variable = config.get(configVariable)
}

Test function

jest.mock('config', () => ({
      default: {
        get: () => jest.fn().mockImplementation(() => {
          const dDate = moment();
          dDate.subtract(1, 'd');
          dDate.format('YYYY-MM-DD');
          return dDate;
        }),
      }
    }));

Could some one please help me with the same and thanks in advance for your time.

1 Answers

i believe it should be

jest.mock('config', 'get').mockImplementation(() => {
  const dDate = moment();
  dDate.subtract(1, 'd');
  return dDate.format('YYYY-MM-DD'); // not sure if you want to return formatted date or not
}));
Related