We are adding unit tests to our javaScript project and we are using jest for it.
As I saw online, we can create _mocks_ folder and add different files we want to mock to this folder.
The problem with this approach is that I couldn’t find a way to create dynamic mocks (I want to create different mocks for the same file/class/function).
This is what I tried:
The original class:
const httpClient = {
get(str){
return str;
}
};
module.exports = { httpClient }
The mock file in _mocks_ :
const httpClient = {
get(str){
return 'a';
}
};
module.exports = { httpClient }
The mock in the test file (named project.test.js):
const { httpClient } = require('./httpClient');
describe('fetchAndProcessUserData', () => {
jest.mock('httpClient', () => ({
...jest.requireActual('./httpClient.js'),
get: jest.fn().mockImplementation((str) => 'b')
}));
it('string should return b', () => {
const returnValue = httpClient.get('not good');
expect(returnValue).toBe('b');
});
});
I also tried writing the mock code before the ‘describe’ in the ‘describe’ and in the test itself (the it block)
Some other jest functions I tried:
- get: jest.fn().mockReturnValue(‘return this’)
- get: jest.fn(() => ‘return this’)
For some reason it always run the original get() function and not the mock one.
This is the configuration I’m using, incase it’s any help:
const { defaults } = require('jest-config')
module.exports = {
...defaults,
rootDir: '.',
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node'],
moduleDirectories: ['node_modules'],
automock: false
};
I would appreciate any help 🙂