玩笑完成回调不可分配给 ProvidesCallback 或未定义类型的参数

Ard*_*ian 6 node.js jestjs typescript-typings ts-jest

我正在尝试用 jest 创建一个测试,我想使用done()回调,但 Typescript 不接受它,我尝试使用 type anyjest.DoneCallback或者不保留任何类型,但再次不起作用。有什么解决方案或想法吗?

错误截图

it('implements optimistic concurrency control', async (done: any) => {
  const ticket = Ticket.build({
    title: 'Concert 123423',
    price: 5,
    userId: '123'
  });
  await ticket.save();
  
  const firstInstance = await Ticket.findById(ticket.id);
  const secondInstance = await Ticket.findById(ticket.id);

  firstInstance!.set({ price: 10 });
  secondInstance!.set({ price: 15 });

  await firstInstance!.save();

  try {
    await secondInstance!.save();
  } catch (err) {
    console.log(err);
    return done();
  }
  throw new Error('Should not reach this point');
});
Run Code Online (Sandbox Code Playgroud)

Too*_*4u 7

您可以选择使用回调Promise或回调。在您的情况下,您希望使用 async/await,因为您在save()继续流程之前正在等待方法。

您的代码已更新:

it('implements optimistic concurrency control', async () => {
  const ticket = Ticket.build({
    title: 'Concert 123423',
    price: 5,
    userId: '123'
  });
  await ticket.save();
  
  const firstInstance = await Ticket.findById(ticket.id);
  const secondInstance = await Ticket.findById(ticket.id);

  firstInstance!.set({ price: 10 });
  secondInstance!.set({ price: 15 });

  await firstInstance!.save();

  try {
    await secondInstance!.save();
  } catch (err) {
    console.log(err);
    return;
  }
  throw new Error('Should not reach this point');
});
Run Code Online (Sandbox Code Playgroud)

以下是使用回调的示例:

it('some asynchronous test', (done) => {
  request(app)
    .get('/endpoint')
    .expect(200)
    .expect((res) => {
       // insert some code stuff here
    })
    // The callback function is passed in so it will call
    // it once it finishes the asynchronous code
    .end(done)
})
Run Code Online (Sandbox Code Playgroud)

另外,您不必指定回调的类型,它应该被推断。如果你愿意的话也可以。