gpt4 book ai didi

javascript - sinon stub 无法识别对 stub 的调用

转载 作者:行者123 更新时间:2023-11-30 19:41:26 26 4
gpt4 key购买 nike

这是要测试的代码:

    const AWS = require('aws-sdk');
const { APPLICATIONS, NOTIFICATION_FREQUENCIES } = require('./config');

exports.createHandler = ({ notificationService }) => async (event, context) => {

try{
Object.values(APPLICATIONS).forEach(async appId => {

const notifications = await notificationService
.getNotificationsByApplication(appId);



const dailyNotifications =notifications.filter(
e =>
e.frequency === NOTIFICATION_FREQUENCIES.DAILY,
);

console.log('dailyNo', dailyNotifications);

const dailyTemplate = notificationService.prepareDailyTemplate(
dailyNotifications
);
console.log('dailyTemplate', dailyTemplate);

notificationService.notifyToAdmin(dailyTemplate);
});
}
catch(err) {
console.log(err);
}

};

这是我使用 sinon 进行的测试:

const sinon = require('sinon');
const { APPLICATIONS, NOTIFICATION_FREQUENCIES } = require('../lib/config');
describe('Daily notifier tests', () => {

it('should prepare daily template for each of the applications', () => {

const notificationService = require('../lib/notificationService').createHandler({
commands: {},
simpleMailService: {},
});

const notifications = [
{
type: 'create_order',
frequency: NOTIFICATION_FREQUENCIES.DAILY,
},
{
type: 'create_order',
frequency: NOTIFICATION_FREQUENCIES.DAILY,
},
{
type: 'create_order',
frequency: NOTIFICATION_FREQUENCIES.MONTHLY,
},
];
const template = 'some html template as string';

sinon.stub(notificationService, 'getNotificationsByApplication').resolves(notifications);
sinon.stub(notificationService, 'prepareDailyTemplate').returns(template);
sinon.stub(notificationService, 'notifyToAdmin');

const sut = require('../lib/dailyNotifier').createHandler({
notificationService,
});

const event = {};
const context = {};


sut(event, context);

const dailyNotifications = [
{
type: 'create_order',
frequency: NOTIFICATION_FREQUENCIES.DAILY,
},
{
type: 'create_order',
frequency: NOTIFICATION_FREQUENCIES.DAILY,
}
];

sinon.assert.calledOnce(notificationService.prepareDailyTemplate);
sinon.assert.calledWith(notificationService.notifyToAdmin, template);


});

});

根据 sinon 方法 prepareDailyTemplate 根本没有被调用(0 次),但是当我执行测试时我什至可以看到 console.log 'dailyTemplate',这意味着该方法已经执行了一次。错误信息:

AssertError: expected prepareDailyTemplate to be called once but was called 0 times

我做错了什么?

最佳答案

sut 是由 createHandler 创建的 async 函数,因此它返回一个 Promise

你只需要await它返回的Promise:

it('should prepare daily template for each of the applications', async () => {  // <= async

// ...

await sut(event, context); // <= await

// ...

sinon.assert.calledOnce(notificationService.prepareDailyTemplate); // Success!
});

关于javascript - sinon stub 无法识别对 stub 的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55346777/

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