I’ve gone through the official Jest docs around manual mocking but I can’t quite make sense of it.
I have a file that exports an object of computed values
utils.js
export const getCalculatedValues = (stuff) => ({
val1: 'val1',
val2: 'val2',
...
});
I am then using this within several other files that I am attempting to test – For example:
usage.js
import {getCalculatedValues} from './utils';
export const doSomething = () => getCalculatedValues('some-val');
So far, I have managed to mock the original getCalculatedValues
usage.test.js
jest.mock('./utils', () => ({
__esModule: true,
getCalculatedValues: {
val1: 123,
val2: 321,
...
}
}));
// Assume this passes ;-)
it('Should return mock values', () => {
const res = doSomething();
expect(res.val1).toEqual(123);
});
As mentioned previously, I am using getCalculatedValues
in several different files which would mean that I am needing to perform the jest.mock
of it within each of their test files, which is a lot of duplication.
I am trying to get my head around the "manual mocking" aspect of Jest but I can’t seem to understand what I should be doing…
I understand that I should create a file within a __mocks__
directory, but from there, I’m not entirely sure what should go in that file…
2
Answers
I feel my confusion came from the official Jest docs around the issue as they showed performing a manual mock on both a dependency and also a file at the same time.
I took a bit of inspiration from a Youtube tutorial I saw that showed performing a manual mock on a file only.
So as the docs say, you must create a mock for the thing you're attempting to mock within the same directory level but within its own
__mocks__
directory.So for me, say we had a file structure like
given we are wanting to mock the functionality within
/src/utils/utils.js
and not in/other-files/usage
we should create the__mocks__
directory and__mocks__/utils.js
within/src/utils
The content of
/__mocks__/utils.js
should mirror the contents of the original file you are mocking. At least, the parts you want to mock and return the mock value you are looking for.mocks/utils.js
Then, we just have to mock it within the
/other-files/usage.test.js
fileAnd that should be it!
A good check is to do a
console.log
of the value you are wanting to check.Just import the file that you are trying to mock on the global level of the test server.