Unit testing NestJS Jest测试期望最终捕获
我是NestJS的新手,在我尝试运行此代码之前,我已经使用包括NestJS官方网站在内的几个网站的示例为我的服务/控制器编写了一个基本单元测试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
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)
来正确解析方法并测试结果