How to mock an exported const in jest

后端 未结 8 1792
借酒劲吻你
借酒劲吻你 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:32

    Instead of Jest and having trouble with hoisting etc. you can also just redefine your property using "Object.defineProperty"

    It can easily be redefined for each test case.

    This is a pseudo code example based on some files I have:

    From localization file:

    export const locale = 'en-US';
    

    In another file we are using the locale:

    import { locale } from 'src/common/localization';
    import { format } from 'someDateLibrary';
    
    // 'MMM' will be formatted based on locale
    const dateFormat = 'dd-MMM-yyyy';
    
    export const formatDate = (date: Number) => format(date, dateFormat, locale)
    
    

    How to mock in a test file

    import * as Localization from 'src/common/localization';
    import { formatDate } from 'src/utils/dateUtils';
    
    describe('format date', () => {
            test('should be in Danish format', () => {
                Object.defineProperty(Localization, 'locale', {
                    value: 'da-DK'
                });
                expect(formatDate(1589500800000)).toEqual('15-maj-2020');
            });
            test('should be in US format', () => {
                Object.defineProperty(Localization, 'locale', {
                    value: 'en-US'
                });
                expect(formatDate(1589500800000)).toEqual('15-May-2020');
            });
    });
    

提交回复
热议问题