简体   繁体   English

如何测试 promise 中调用的方法

[英]How to test method called in promise

I have a function that saves an entity and in the promise i want to check the delete is called.我有一个 function 保存一个实体,在 promise 我想检查删除是否被调用。

In my jest test it whizzes past and can't think how to test it在我开玩笑的测试中,它呼啸而过,无法思考如何测试它

Here is the partial snippets, it all works, Promises called etc. just can't figure how to test that 'deleteMessage' is called这是部分片段,一切正常,调用了 Promises 等等。只是不知道如何测试调用了“deleteMessage”

              this.service
              .save(entity)
              .then(() => {
                this.sqsQueue.deleteMessage(message.ReceiptHandle!);
              })
              .catch((error) => {
                this.log.error('Error saving');
              });

In my test i use在我的测试中我使用

service.save = jest.fn().mockResolvedValue(null);
expect(sqsQueue.deleteMessage).toHaveBeenNthCalledWith(
      1,
      deleteItem1.ReceiptHandle
    );

As mentioned because it's a Promise, the test doesn't wait for the save and and runs the expect which of course fails because the function has not run yet.如前所述,因为它是 Promise,测试不会等待保存并运行预期,这当然会失败,因为 function 尚未运行。

test('item is deleted', () => {
  return service.save().then(() => {
   // Put your expects here
   });
});

For more info see the docs: https://jestjs.io/docs/en/asynchronous有关更多信息,请参阅文档: https://jestjs.io/docs/en/asynchronous

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM