Search code examples
javascriptnode.jsjestjsnode-config

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('* * * * *');

Solution

  • 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