【问题标题】:[]' is missing the following properties from type 'Promise<Cats[]>': then, catch, [Symbol.toStringTag], finally ts(2739)[]' 缺少类型 'Promise<Cats[]>' 的以下属性:然后,catch,[Symbol.toStringTag],最后是 ts(2739)
【发布时间】:2020-12-31 20:07:17
【问题描述】:

我是打字稿和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);
  });
})
});

【问题讨论】:

  • 似乎 getCats 应该返回一个承诺,但你的模拟替代品没有。
  • @VLAZ 那么解决方案是什么?因为我是新来的

标签: typescript jestjs nestjs


【解决方案1】:

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

  1. 使用mockResolvedValue() 而不是mockImplementation()。这将使 Jest 对您告诉它的内容做出承诺。
  2. 使用mockImplementation(() =&gt; new Promise((resolve, reject) =&gt; resolve(result)))返回一个promise而不是结果。^

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

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

【讨论】:

  • 也可行async () =&gt; result() =&gt; Promise.resolve(result)
  • .then((result) => { console.log('',result); resolve(result); }).catch((err) => { console.log('',呃); }););对吗?
猜你喜欢
  • 2021-01-14
  • 2022-11-21
  • 2020-09-12
  • 2021-04-02
  • 2019-06-21
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多