NestJS Jest 测试期待然后终于赶上
NestJS Jest test expecting then catch finally
我是 NestJS 的新手,并且已经使用包括官方 NestJS 网站在内的几个网站的示例为我的 service/controller 编写了一个基本单元测试,甚至在我尝试 运行 这段代码之前,
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.
我正在从我的控制器返回一个 Promise,但不知何故,编译器期待 try catch finally 在某个地方,但我不知道它应该去哪里。
如果 service.findAll
通常 return 是一个承诺,那么您也应该使模拟 return 成为一个承诺。您可以使用 jest.spyOn(service, 'findAll').mockResolvedValue(result)
执行此操作。现在在您的测试中,您可以 expect(controller.findAll()).resovles.toEqual(result)
使方法正确解析并测试结果。
我是 NestJS 的新手,并且已经使用包括官方 NestJS 网站在内的几个网站的示例为我的 service/controller 编写了一个基本单元测试,甚至在我尝试 运行 这段代码之前,
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.
我正在从我的控制器返回一个 Promise,但不知何故,编译器期待 try catch finally 在某个地方,但我不知道它应该去哪里。
如果 service.findAll
通常 return 是一个承诺,那么您也应该使模拟 return 成为一个承诺。您可以使用 jest.spyOn(service, 'findAll').mockResolvedValue(result)
执行此操作。现在在您的测试中,您可以 expect(controller.findAll()).resovles.toEqual(result)
使方法正确解析并测试结果。