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

2

18

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

Cule answered 29/6, 2021 at 17:21 Comment(2)
Should just be Promise.resolve() instead of Promise.resolve(void)Mcgary
Try to avoid using void operatorSwiercz
V
32

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.

Valle answered 29/6, 2021 at 18:38 Comment(0)
H
8

You can mock a function that returns Promise<void> with:

jest.fn().mockResolvedValue(undefined)

If you try to capture the return value of a void function, you get undefined:

function foo(): void {
  console.log('foo called');
}

console.log(foo());

// foo called
// undefined

Additionally, Promise<void> appears to be the same as Promise<undefined>:

console.log(Promise.resolve());
// Promise { undefined }

console.log(Promise.resolve(undefined));
// Promise { undefined }

undefined is compatible with void and can be the resolved value:

interface Bar {
  foo(): Promise<void>;
}

describe('StackOverflow', () => {
  test('mock Promise<void>', async () => {
    const mockBar: Bar = {
      foo: jest.fn().mockResolvedValueOnce(undefined),
    };
    await mockBar.foo();
  });
});
Homework answered 28/10, 2022 at 2:8 Comment(5)
Or to simplify the expression even further, jest.fn().mockResolvedValue().Peebles
@PriiduNeemre Expected 1 argument.Divulgate
@Heisenberg: which defaults to undefined when you omit it.Peebles
@PriiduNeemre the argument has no default value, at least not in typescript , the definition is : mockResolvedValue(value: ResolvedValue<T>) and calling it with no parameter causes error TS2554Divulgate
@Heisenberg: Ah, yes. In TypeScript, it is a mandatory parameter and would probably work like this for void functions only.Peebles

© 2022 - 2025 — McMap. All rights reserved.