Jestjs 如何在每个案例的基础上使用Jest模拟命名常量导出?

Jestjs 如何在每个案例的基础上使用Jest模拟命名常量导出?,jestjs,Jestjs,我有一个模块constants.js,它返回多个常量对象: export const SERVER = { HOST: 'localhost', PORT: 8000, }; export const PATHS = { LOGIN: '/login', LOGOUT: '/logout', }; 我正在使用,为了使用Jest进行并行测试,我必须在每个it()测试用例上使用不同的端口。因此,我想更改beforeach()上的SERVER.PORT的值 这是我到目前为止所做的,

我有一个模块
constants.js
,它返回多个常量对象:

export const SERVER = {
  HOST: 'localhost',
  PORT: 8000,
};

export const PATHS = {
  LOGIN: '/login',
  LOGOUT: '/logout',
};
我正在使用,为了使用Jest进行并行测试,我必须在每个
it()
测试用例上使用不同的端口。因此,我想更改
beforeach()
上的
SERVER.PORT
的值

这是我到目前为止所做的,但不起作用:

beforeEach(() => {
  port = getRandomPort();

  jest.doMock('./constants', () => ({
    SERVER: {
      PORT: port,
    },
  })
});
当加载
constants.js
时,被测模块将使用实际值而不是模拟值加载它。所以这是行不通的

我还尝试使用
jest.mock()
而不是
jest.doMock()
并返回一个mock函数,因此我可以更改
.mockReturnValue()
,但是由于
constants.js
不导出函数,而是导出对象,这样做毫无意义,因此也不起作用


如何实现这一点?

我最终为常量
\uuuuumocks\uuuuu/constants.js创建了一个模拟文件,并要求在其中包含实际文件:

// __mocks__/constants.js
const actualConstants = require.requireActual('../constants');

export default {
  ...actualConstants,

  aSingleConstant: 'mocked value',
};