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

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)".



Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aleksxor
Solution 2 Yogesh Umesh Vaity