I'm using jest and Typescript. I have this exported function in a service file ...
export async functionprocessData(
data: MyDataI,
): Promise<
...
Then in a separate file (run-my-process.ts) that I call via npm cli, I have this
import {processData } from '../services/my.service';
...
processData(data)
.then((result) => {
Now I would like to mock the "processData" function from jest, so I tried 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.');
But the test dies with the error
ERROR [1624482717612] (71310 on localhost): Cannot read property 'then' of undefined
So it seems my function, processData, is somehow evaluating to "undefined" when called with an argument. What's the right way to mock my function to return a Promise and get my Jest test to pass?