Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jest, how do I mock an exported function to return a Promise rather than undefined?

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?

like image 294
Dave Avatar asked Nov 06 '22 01:11

Dave


2 Answers

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: {} }));    
like image 138
Transformer Avatar answered Nov 11 '22 04:11

Transformer


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()

like image 30
Hassan Naqvi Avatar answered Nov 11 '22 04:11

Hassan Naqvi