How to mock an exported const in jest

后端 未结 8 1777
借酒劲吻你
借酒劲吻你 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条回答
  •  -上瘾入骨i
    2020-12-23 19:25

    Thanks to @Luke I was able to expand on his answer for my needs. I had the requirements of:

    • Only mocking certain values in the file - not all
    • Running the mock only inside a single test.

    Turns out that doMock() is like mock() but doesn't get hoisted. In addition requireActual() can be used to grab original data.

    My config.js file - I need to mock only part of it

    export const SOMETHING = 'blah'
    export const OTHER = 'meh'
    

    My test file

    // import { someFunc } from  'some/file' // This won't work with doMock - see below
    describe('My test', () => {
    
      test('someFunc() does stuff', async () => {
    
        // Here I mock the config file which gets imported somewhere deep in my code
        jest.doMock('config.js', () => {
    
          // Grab original
          const originalModule = jest.requireActual('config')
    
          // Return original but override some values
          return {
            __esModule: true, // Depends on your setup
            ...originalModule,
            SOMETHING: 'boom!'
          }
        })
    
        // Because `doMock` doesn't get hoisted we need to import the function after
        const { someFunc } = await import(
          'some/file'
        )
    
        // Now someFunc will use the original config values but overridden with SOMETHING=boom!
        const res = await someFunc()
      })
    })
    

    Depending on other tests you may also need to use resetModules() somewhere such as beforeAll or afterAll.

    Docs:

    • doMock
    • requireActual
    • resetModules

提交回复
热议问题