Reputation: 12523
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('* * * * *');
Upvotes: 3
Views: 4455
Reputation: 33
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)
})
Upvotes: 0
Reputation: 32158
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
Upvotes: 4