How to mock an exported const in jest

后端 未结 8 1703
借酒劲吻你
借酒劲吻你 2020-12-23 18:35

I have a file that relies on an exported const variable. This variable is set to true but if ever needed can be set to false manually

8条回答
  •  有刺的猬
    2020-12-23 19:21

    Unfortunately none of the posted solutions worked for me or to be more precise some did work but threw linting, TypeScript or compilation errors, so I will post my solution that both works for me and is compliant with current coding standards:

    // constants.ts
    // configuration file with defined constant(s)
    export const someConstantValue = true;
    
    // module.ts
    // this module uses the defined constants
    import { someConstantValue } from './constants';
    
    export const someCheck = () => someConstantValue ? 'true' : 'false';
    
    // module.test.ts
    // this is the test file for module.ts
    import { someCheck } from './module';
    
    const mockSomeConstantValueGetter = jest.fn();
    jest.mock('./constants', () => ({
      get someConstantValue() {
        return mockSomeConstantValueGetter();
      },
    }));
    
    describe('someCheck', () => {
      it('returns "true" if someConstantValue is true', () => {
        mockSomeConstantValueGetter.mockReturnValue(true);
        expect(someCheck()).toEqual('true');
      });
    
      it('returns "false" if someConstantValue is false', () => {
        mockSomeConstantValueGetter.mockReturnValue(false);
        expect(someCheck()).toEqual('false');
      });
    });
    

提交回复
热议问题