In Jest, how do I mock a Promise of void?

Viewed 6929

I'm using Jest and Typescript. I have a async function that returns nothing (void). How do I mock returning void? I tried the below

const myMockFn = jest.fn().mockImplementationOnce(() => Promise.resolve(void));
jest.mock('../config', () => ({
  setup: async () =>
  myMockFn(),
}));

but I get the compilation error

Expression expected.

related to "Promise.resolve(void)".

2 Answers

void used here in value position is javascript operator. It is a unary operator i.e. it accepts a single argument. Thus the error.

void as a typescript type should be used in type position to express that function return value will not be observed.

const myMockFn = jest.fn().mockImplementationOnce(() => Promise.resolve());

That's enough to mock a function with Promise<void> return type.

For shorter syntax, you can also use the mockResolvedValue functions:

// For resolved promises
const myMockFn = jest.fn().mockResolvedValueOnce({})  

// For rejected promises
const myMockFn = jest.fn().mockRejectedValueOnce(new Error('Your message'))  
Related