[]' 缺少类型 'Promise<Cats[]>' 中的以下属性:然后,catch,[Symbol.toStringTag],最后 ts(2739)

jac*_*lsi 3 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);
  });
})
});
Run Code Online (Sandbox Code Playgroud)

Jay*_*iel 6

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

  1. 使用mockResolvedValue()代替mockImplementation(). 这将使 Jest 返回你告诉它的承诺。
  2. 用于mockImplementation(() => new Promise((resolve, reject) => resolve(result)))返回承诺而不是结果。^

这两个做同样的事情,所以选择是你的,但第一个绝对更容易阅读。

^ 正如 VLAZ 所指出的,这可以是任何返回承诺的东西,包括使用mockImplementation(async () => result)mockImplementation(() => Promise.resolve(result))

  • 也可行 `async () =&gt; result` 或 `() =&gt; Promise.resolve(result)` (2认同)