Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing NestJS Jest测试期望最终捕获_Unit Testing_Promise_Jestjs_Es6 Promise_Nestjs - Fatal编程技术网

Unit testing NestJS Jest测试期望最终捕获

Unit testing NestJS Jest测试期望最终捕获,unit-testing,promise,jestjs,es6-promise,nestjs,Unit Testing,Promise,Jestjs,Es6 Promise,Nestjs,我是NestJS的新手,在我尝试运行此代码之前,我已经使用包括NestJS官方网站在内的几个网站的示例为我的服务/控制器编写了一个基本单元测试 it('should be defined', async () => { const result:MyEntity[] = [{"test1":"value1"},{"test1":"value2"}]; jest.spyOn(service, 'findAll').mockImplementation(() => re

我是NestJS的新手,在我尝试运行此代码之前,我已经使用包括NestJS官方网站在内的几个网站的示例为我的服务/控制器编写了一个基本单元测试

it('should be defined', async () => {

    const result:MyEntity[] = [{"test1":"value1"},{"test1":"value2"}];
    jest.spyOn(service, 'findAll').mockImplementation(() => result);

    expect(await controller.findAll()).toBe(result);
  });
我看到以下错误

Type 'MyEntity[]' is missing the following properties from type 'Promise<MyEntity[]>': then, catch, [Symbol.toStringTag], finallyts(2739)
index.d.ts(1163, 33): The expected type comes from the return type of this signature.
类型“MyEntity[]”缺少类型“Promise”中的以下属性:然后,catch,[Symbol.toStringTag],finallyts(2739)
index.d.ts(1163,33):预期类型来自此签名的返回类型。

我正在从我的控制器返回一个承诺,但不知何故,编译器希望最终在某个地方尝试捕获,但我不知道这应该去哪里

如果
service.findAll
通常返回一个承诺,那么您应该使模拟返回也成为一个承诺。您可以使用
jest.spyOn(服务,'findAll').mockResolvedValue(结果)
来实现这一点。现在,在您的测试中,您可以执行
expect(controller.findAll()).resovles.toEqual(result)
,以使方法正确解析并测试结果。

如果
service.findAll
通常返回承诺,那么您也应该使模拟返回承诺。您可以使用
jest.spyOn(服务,'findAll').mockResolvedValue(结果)
来实现这一点。现在,在您的测试中,您可以执行
expect(controller.findAll()).resovles.toEqual(result)
来正确解析方法并测试结果