When using it.each it gives a type error Jest

Viewed 379

When I use it.each from jest I get an error when defining the callback for it

Argument of type '(n: any) => Promise<void>' is not assignable to parameter of type '() => any'.ts(2345)

The code with the it.each is outlined below:

it.each([null, undefined, []])('should throw Http exception with expected exception message', async (n) => {
  await expect(() => service.check(n)).rejects.toThrow(
    new HttpException(
      {
        statusCode: HttpStatus.BAD_REQUEST,
        message: "Nothing to check",
        error: HttpStatus.BAD_REQUEST,
      },
      HttpStatus.BAD_REQUEST,
    ),
  );
});

The jest types and the jest version are shown below if it helps:

"@types/jest": "^27.4.1",
"jest": "^27.2.5",

The issue is with the async (n) => ... any help is much appreciated, thanks!

1 Answers

You aren't returning a result from your async function.

Your async fat-arrow function is defined with curly braces, which means it requires an explicit return statement to return a value.

// Curly braces requires explicit return
() => {}

// This doesn't return anything because there is no `return` statement
() => {
  5;
}

// This returns a number
() => {
  return 5;
}
// This fat arrow syntax has an implicit return
() => ()

// These have an implicit return and are equivalent
() => 5
() => (5)

You can either use an explicit return:

// Use explicit return
it.each([null, undefined, []])('should throw Http exception with expected exception message', async (n) => {
  return await expect(() => service.check(n)).rejects.toThrow(
    new HttpException(
      {
        statusCode: HttpStatus.BAD_REQUEST,
        message: "Nothing to check",
        error: HttpStatus.BAD_REQUEST,
      },
      HttpStatus.BAD_REQUEST,
    ),
  );
});

Or remove the curly braces.

In this second case I've removed the curly braces and wrapped the function body in round brackets to make the grouping more explicit.

// Use implicit return - note curly braces were changed to round brackets
it.each([null, undefined, []])('should throw Http exception with expected exception message', async (n) => (
  await expect(() => service.check(n)).rejects.toThrow(
    new HttpException(
      {
        statusCode: HttpStatus.BAD_REQUEST,
        message: "Nothing to check",
        error: HttpStatus.BAD_REQUEST,
      },
      HttpStatus.BAD_REQUEST,
    ),
  );
));
Related