2

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('* * * * *');
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
nano_nano
  • 12,351
  • 8
  • 55
  • 83
  • 1
    Yes, several ways, either supply a [mock implementation](https://jestjs.io/docs/en/mock-functions#mock-implementations) or, if you can rely on the order, [`mockReturnValueOnce`](https://jestjs.io/docs/en/mock-function-api#mockfnmockreturnvalueoncevalue). – jonrsharpe Nov 13 '20 at 10:00

2 Answers2

4

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

Teneff
  • 30,564
  • 13
  • 72
  • 103
0

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)
        })
Boris Wild
  • 33
  • 6