typescript - []' is missing the following properties from type ' Promise<Cats[]>' : then, catch, [Symbol.toStringTag], 最后是 ts(2739)

标签 typescript jestjs nestjs

我是 typescript 和 nestjs 的新手,我正在尝试学习 nest js,但是当我尝试对我的代码进行单元测试时,结果变量给了我标题中显示的错误?任何人都可以帮助我尝试找出我在这里做错了什么。

describe('cats', () => {
  let controller: CatsController;
  let service: CatsService;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [DeliveryController],
    }).compile();

    controller = module.get<CatsController>(CatsController);
  });
describe('', () => {
  it('should return an array of cats', async () => {
    const result = [
{
id: "1",
name: "Cat",
type: "hybrid"
}
          ];
    jest.spyOn(service, 'getCats').mockImplementation(() => result); //'result' in this line shows error

    expect(await controller.getAllCats()).toBe(result);
  });
})
});

最佳答案

您正在返回一个数组,但您的函数是 async ,这意味着它应该返回数组的 Promise。有两种方法可以解决这个问题。

  • 使用 mockResolvedValue()而不是 mockImplementation() .这将使 Jest 返回你告诉它的 promise 。
  • 使用 mockImplementation(() => new Promise((resolve, reject) => resolve(result)))返回 promise 而不是结果。^

  • 这两个做同样的事情,所以选择是你的,但第一个绝对更容易阅读。
    ^ 正如 VLAZ 所指出的,这可以是任何返回 promise 的东西,包括使用 mockImplementation(async () => result)mockImplementation(() => Promise.resolve(result))

    关于typescript - []' is missing the following properties from type ' Promise<Cats[]>' : then, catch, [Symbol.toStringTag], 最后是 ts(2739),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63878594/

    相关文章:

    javascript - 使用 Observables 在组件中发生更改后如何再次从 API 获取数据?

    Angular 从子组件传递值以禁用父组件中的按钮

    reactjs - 在 Jest 中测试 Axios

    javascript - 如何在 Jest React 测试中等待 promise ?

    node.js - 分析我的 NodeJS 服务器显示它挂起......但是如何找出原因?

    javascript - 从 jsonwebtoken 中提取到期日期时间

    command-line-interface - NestJS CLI 输出垃圾

    javascript - 尝试发布 npm 包时出现 "npm ERR! invalid semver"

    typescript - 如何在 Typescript 枚举中查找具有值的键?

    javascript - Jest 报道不算在报道中抛出错误