In my project, I am using jest along with Typescript. There is a function called "processData" that is exported from a service file...
export async function processData(
data: MyDataI,
): Promise<
...
In another file (run-my-process.ts) which is called via npm cli, the "processData" function is imported like this:
import {processData} from '../services/my.service';
...
processData(data)
.then((result) => {
I wanted to mock the "processData" function in jest, so I attempted this:
jest.mock('../services/my.service', () => {
// The mock returned only mocks the generateServerSeed method.
const actual = jest.requireActual('../services/my.service');
return {
...actual,
processData: jest.fn().mockReturnValue(Promise.resolve({
dataInserted: 1,
}))
}
});
...
describe('calls the job', function () {
it('invokes the function', async () => {
...
jest.spyOn(process, 'exit').mockImplementationOnce(() => {
throw new Error('process.exit() was called.');
});
expect(() => {
require('./run-my-process');
}).toThrow('process.exit() was called.');
However, the test fails and throws the error:
ERROR [1624482717612] (71310 on localhost): Cannot read property 'then' of undefined
It seems like the function "processData" is being evaluated as "undefined" when called with an argument. What is the correct way to mock this function to return a Promise and make my Jest test pass?