代码之家  ›  专栏  ›  技术社区  ›  DorkMonstuh

使用它的时候。每一个都会给出一个类型错误笑话

  •  2
  • DorkMonstuh  · 技术社区  · 4 年前

    当我使用它的时候。在为它定义回调时,我从jest中得到的每一个都是一个错误

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

    代码和它在一起。每一项都概述如下:

    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,
        ),
      );
    });
    

    jest类型和jest版本如下所示(如果有帮助):

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

    问题在于 async (n) => ... 非常感谢您的帮助,谢谢!

    1 回复  |  直到 4 年前
        1
  •  0
  •   Sly_cardinal    4 年前

    您没有从异步函数返回结果。

    异步fat arrow函数是用大括号定义的,这意味着它需要显式的return语句来返回值。

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

    您可以使用显式返回:

    // 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,
        ),
      );
    });
    

    或者去掉花括号。

    在第二种情况下,我删除了大括号,并将函数体包装在圆括号中,以使分组更加明确。

    // 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,
        ),
      );
    ));