Consider this scenario where a module is defined as follows:
// utils.ts
function innerFunction() {
return 28;
}
function testing() {
return innerFunction();
}
export {testing}
To write a unit test for the testing
function and mock the return value of
innerFunction</code, you can specify a fixed value for any call to <code>innerFunction
. This can be achieved using the following code snippet:
jest.mock('../utils', () => {
const originalModule = jest.requireActual('../utils');
return {
...originalModule,
innerFunction: jest.fn().mockReturnValue(33),
};
});
import { testing } from '../utils';
it('should validate properly', () => {
expect(testing()).toBe(33);
});
Despite the expectation that jest.requireActual
would read all functions and set
innerFunction: jest.fn().mockReturnValue(33)</code to always return <code>33
, it doesn't seem to work in practice based on the provided experiment.
In reality, innerFunction
returns 28
, but within Jest environment, we hope to control innerFunction
to resolve to the desired value.