我正在将议程用于后台作业,并且我正在尝试测试定义方法以确保 1.) 议程.define 被调用和 2.) 议程内部的方法被调用 (triggerSend)。
我已经包含了我用来进行此测试的四个文件:1.) 议程作业定义 2.) triggerSend 实用程序函数 3.) sinon 存根 4.) 实际测试。我将非常感谢您提供的任何和所有帮助!
照原样,agenda.define 被调用了两次,我可以看到 triggerSend 的日志被调用了两次。第一个 triggerSend 显示一个作业对象,第二个 triggerSend 日志显示undefined
.
我想弄清楚如何使用 sinon 准确捕获被调用的议程定义和triggerSend。
议程/campaigns/jobs/test.js(带有议程.define的工作):
const triggerSend = require('../../../campaign/trigger.js');
module.exports = function(agenda) {
agenda.define('test', function(job,done){
console.log("agenda.define called!");
triggerSend(job)
.then(done).catch(done);
});
}
campaign/ trigger.js triggerSend 实用程序函数在议程定义中调用:
module.exports = async function(job) {
console.log("triggerSend for job: ", job);
// Legacy procedural code
}
固定装置/存根/index.js
const sinon = require('sinon');
module.exports = {
DefineAgenda: function(agenda, jobMock) {
return sinon.stub(agenda, 'define').callsFake(function(job, done) {
/*
*This is to call the function (job, done) callback from agenda.define,
*it results in triggerSend being actually called (not the stub) but it
*also results in agenda.define being called twice.
*/
return arguments[1](jobMock, done);
});
},
TriggerSend: function(triggerSend, jobMock) {
return sinon.stub(triggerSend, 'default').callsFake(function(job) {
console.log("triggerSend arguments: ", arguments)
return arguments[1](jobMock);
});
}
}
test.test.js:
const chai = require("chai");
const expect = chai.expect;
const agenda = require('../../../modules/agenda').campaignInstance();
const triggerSend = require('../../../campaign/trigger.js');
const triggerSendObj = { default: triggerSend };
const DefineAgenda = require('../../../fixtures/stubs').DefineAgenda;
const TriggerSend = require('../../../fixtures/stubs').TriggerSend;
const jobMock = require('../../../fixtures/mocks/jobs').campaign;
const testJob = require('../../../agenda/campaigns/jobs/test.js');
describe('Campaign agenda.define', function() {
before(function() {
this.DefineAgendaStub = DefineAgenda(agenda, jobMock);
this.TriggerSendStub = TriggerSend(triggerSendObj, jobMock);
});
it('is called', async function() {
//call agenda job for test
testJob(agenda);
//assertions
expect(agenda.define.called).to.be.true;
expect(triggerSendObj.default.called).to.be.true;
})
});