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?
Try this with whatever data you may need to adapt, a nice article here
processData: jest.fn(() => Promise.resolve({ data: {}}))
To export
export default jest.fn(() => Promise.resolve({ data: {} }));
A much simpler approach could be:
import * as myService from '../services/my.service';
jest.spyOn(myService, 'processData').mockResolvedValue({ dataInserted: 1 });
Using this, you can bypass the complex mocking you are trying to do using jest.mock()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With