-1

I have the following Javscript code:

const authenticationTypeMapping = (payload) => {
  const { API_CONFIG } = process.env;

  try {
    const apiConfig = JSON.parse(API_CONFIG.toString('utf8'));
    // set authenticationType to Federated for production
    if (apiConfig.API_BASE_URL.includes('prd')) {
      payload.authenticationTypeName = 'Federated';
      // set authenticationType to Federated for dev or UAT
    } else if (apiConfig.API_BASE_URL.includes('dev') || apiConfig.API_BASE_URL.includes('uat')) {
      payload.authenticationTypeName = 'Basic';
    }
  } catch (err) {
    console.log(`Failed to map authenticationType. Unable to parse Secret: ${err}`);
  }
  return payload;
};

I have problem to cover unit test using jesty for the code for the lines inside try block.

If statement depends on external variable "apiConfig.API_BASE_URL" of "process.env" which I don't how to represent to jest code.

it('should call authenticationTypeMapping', async () => {
    const payload = mapper.authenticationTypeMapping(basicPayload);
    expect(payload.authenticationTypeName).toEqual('Basic');
});

What should be added to cover the unit test?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
R.Almoued
  • 219
  • 6
  • 16
  • 1
    Does this answer your question? [Test process.env with Jest](https://stackoverflow.com/questions/48033841/test-process-env-with-jest) – Matt Jan 26 '23 at 01:41
  • also some related info in [Invalidate node cache when using Jest](https://stackoverflow.com/q/48042200/1318694) – Matt Jan 26 '23 at 01:42
  • @Matt what is content of const testedModule = require('../../config/env').default ? – R.Almoued Jan 26 '23 at 01:52

1 Answers1

1

You can set the Environment in the test and check for the same condition in the unit test as follows

it('should call authenticationTypeMapping', async () => {
    process.env.API_BASE_URL = 'prd...'
expect(mapper.authenticationTypeMapping(basicPayload).authenticationTypeName).toEqual('Federated');
    process.env.API_BASE_URL = 'dev...'
expect(mapper.authenticationTypeMapping(basicPayload).authenticationTypeName).toEqual('Basic');
});

Maybe you can have more than one unit tests to make things clear like one to test 'prd' and one to test 'dev'

Shakya Peiris
  • 504
  • 5
  • 11