代码之家  ›  专栏  ›  技术社区  ›  Christopher Francisco

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

  •  3
  • Christopher Francisco  · 技术社区  · 8 年前

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

    export const SERVER = {
      HOST: 'localhost',
      PORT: 8000,
    };
    
    export const PATHS = {
      LOGIN: '/login',
      LOGOUT: '/logout',
    };
    

    我正在使用 PactJS ,为了使用Jest进行并行测试,我必须在每个 it() 测试用例。所以我想改变 SERVER.PORT 在…上 beforeEach()

    这是我目前所拥有的,但不起作用:

    beforeEach(() => {
      port = getRandomPort();
    
      jest.doMock('./constants', () => ({
        SERVER: {
          PORT: port,
        },
      })
    });
    

    加载时,正在测试的模块 常量。js 用实际值而不是模拟值加载它。所以这是行不通的。

    我还尝试使用 jest.mock() 而不是 jest.doMock() 并返回一个模拟函数,这样我就可以更改 .mockReturnValue() 但是自从 常量。js 不导出函数,而是导出对象,这样做没有意义,因此也不起作用。

    我怎样才能做到这一点?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Christopher Francisco    7 年前

    我最终为常量创建了一个模拟文件 __mocks__/constants.js 并要求内部有实际文件:

    // __mocks__/constants.js
    const actualConstants = require.requireActual('../constants');
    
    export default {
      ...actualConstants,
    
      aSingleConstant: 'mocked value',
    };