gpt4 book ai didi

javascript - Chai/诗农 : How to spy on the return value of a promise returned by a function?

转载 作者:行者123 更新时间:2023-12-02 13:43:10 27 4
gpt4 key购买 nike

我正在为 onAfterDelete 设置单元+集成测试:

Assessment.onAfterDelete = async () => {
...

// Log assessment deleted
await Activity.create({
assessmentId,
activityTypeId: ACTIVITY_TYPE.ASSESSMENT_DELETED,
}, options);

...
};

虽然我知道如何测试 Activity.create 被调用,但我真的很想测试 Activity 是否已成功创建。

如果它不是异步的,那么我会使用Sinon.spy,如下所示:

it('logs the assessment deleted activity', async () => {
sinon.spy(Activity, 'create');
await Assessment.onAfterDelete(...);
expect(Activity.create).returned({
activityTypeId: ACTIVITY_TYPE.ASSESSMENT_DELETED,
assessmentId: standardAssessmentData.id,
});
Activity.create.restore();
});

当然,这不起作用,因为 Activity.create 返回一个 Promise。

在谷歌上搜索了 Chai 和 Sinon 的各种风格并 promise 了一个小时后,我还没有找到这个用例的解决方案。如何测试这个返回值?

最佳答案

您可以使用chai-as-promised :

const chai           = require('chai');
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

it('logs the assessment deleted activity', async () => {
sinon.spy(Activity, 'create');
await Assessment.onAfterDelete();

// Make sure `Activity.create()` got called.
expect(Activity.create.called).to.be.true;

// Check the resolved value.
await expect(Activity.create.firstCall.returnValue).to.eventually.equal({
activityTypeId : ACTIVITY_TYPE.ASSESSMENT_DELETED,
assessmentId : standardAssessmentData.id,
});

// Restore the original.
Activity.create.restore();
});

关于javascript - Chai/诗农 : How to spy on the return value of a promise returned by a function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43703628/

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