简体   繁体   中英

mock node config with jest

I introduce myself currently for the first time in jest and nodejs. I am facing the problem that I have to mock two different values from the nodejs config.

jest.mock('config')
mockConfigTtl = require('config').get.mockReturnValue(100);
mockConfigScheduling = require('config').get.mockReturnValue('* * * * *');

the problem is that the second mockReturnValue overwrites the first one. is there any possibility to separate booth mocks from each other?

Maybe with something like:

jest.mock('config')
mockConfigTtl = require('config').get('firstKey').mockReturnValue(100);
mockConfigScheduling = require('config').get('secondKey').mockReturnValue('* * * * *');

Since you would want to ensure your implementation would work with all possible configuration I consider it best to set multiple test scenarios in different describe block and in each of them use mockReturnValue and execute your implementation.

example:

const config = require('config');

jest.mock('config')

describe('my implementation', () => {
  describe('with firstKey 100', () => {
    let result
    beforeAll(() => {
      config.get.mockReturnValue(100)
      result = myImplementation()
    })

    it('should result in ...', () => {
      // your assertion here
    })
  })

  describe('with firstKey different than 100', () => {
    let result
    beforeAll(() => {
      config.get.mockReturnValue(1000)
      result = myImplementation()
    })

    it('should result in ...', () => {
      // your assertion here
    })
  })
})

or in case you want to test even more configuration you may use describe.each

const config = require('config');

jest.mock('config')

describe('my implementation', () => {
  describe.each([
    100,
    200,
    300
  ])('with firstKey: %d', (firstKey) => {
    let result
    beforeAll(() => {
      config.get.mockReturnValue(firstKey)
      result = myImplementation()
    })

    it('should match the snapshot',  () => {
      expect(result).toMatchSnapshot()
    })
  })
})

which would generate a snapshot with the result form your implementation and if it changes the test will fail unless snapshot is updated

You also can use config.get.mockImplementation(()=>'dummyData') to pass data for testing.

If in some cases you need original data you can use this snippet in your tests:

config.get.mockImplementation((key) => {
            const originalModule = jest.requireActual('config')
            return originalModule.get(key)
        })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM