gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:54:21 25 4
gpt4 key购买 nike

我是 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com