0

I have below file with one non exported constant variable.
I am trying to mock the variable value for the purpose of unit testing functions.
This file is common and used across the project, so it is affecting UT of other files as well.

// state.js

// I want to mock value of this variable
const appState = {};

// There are around 20+ functions which generates some values 
// and store in the appState when application runs

export function generateFoo() {
   // Call HTTP request and get result 
   const result = getHttp('/path/foo');
   appState.foo = {
      someValue: 10
   };
}

// Then I have functions which reads + calculate and return 
// Properties fro mthe appState  

export function getFoo() {
   const foo = appState.foo;
   // Do some calculation and return 
   foo.someValue = foo.someValue + 10;
   return foo;
}

What I am trying is, set some default value to appState when running the unit test.
But I am not able to do that.

Solutions that I did try.

Solution #1

const rewire = require('rewire');
const stateRewire = rewire('state.js');
const appState = {
   someValue: 10,
};
stateRewire.__set__('appState', appState);
await stateRewire();

// I get error: TypeError: Assignment to constant variable. 

Solutions #2

jest.mock('state', () => {
  const originalModule = jest.requireActual('state.js');
  return {
    __esModule: true,
    ...originalModule,
    appState: {
      someValue: 10,
    }
  };
});

// It does not refer to mock and gets the original `appState`

Solutions #3

jest.doMock('state', () => {
  const originalModule = jest.requireActual('state.js');

  return {
    __esModule: true,
    appState: {
      someValue: 10,
    },
    ...originalModule
  };
});

I did refer to all the posts in stackoverflow but none of them did help.
Anyone did face this?

User7723337
  • 11,857
  • 27
  • 101
  • 182

0 Answers0