如何覆盖nodejs中外部变量依赖jest中“if语句”的单元测试

5ssjco0h  于 2023-01-28  发布在  Jest
关注(0)|答案(1)|浏览(192)

我有下面的Javascript代码:

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;
};

我有问题,以涵盖单元测试使用jesty的代码行内尝试块。
If语句依赖于“process.env”的外部变量“apiConfig.API_BASE_URL”,我不知道如何将其表示为jest代码。

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

应该添加什么来覆盖单元测试?

js4nwp54

js4nwp541#

可以在测试中设置环境,并在单元测试中检查相同的条件,如下所示

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');
});

也许你可以有一个以上的单元测试来使事情变得清楚,比如一个测试'prd',一个测试'dev'

相关问题