我需要使用node-cron调用一个函数,并希望为此编写单元测试用例。单元测试用例应该能够测试函数是否正在基于模式进行调用。
下面是我的代码
const server = module.exports = {
cronJob:null,
scheduledJob: function (pattern) {
server.cronJob= cron.schedule(pattern, () => {
server.run();
})
},
run: function () {
console.log('run called');
}
}
我正在使用sinon作为测试用例
describe('entry point test suite',()=>{
it('should call function every second',(done)=>{
const pattern= '* * * * * *';
let spy = sinon.spy(server,'run');
server.scheduledJob(pattern);
server.cronJob.Start();
// to do wait for 3 sencond
server.cronJob.Stop();
expect(spy.callCount).eq(3);
})
});
两个问题: 1.除了settimeout之外,我还必须等待3秒才能使cron作业每秒运行3次,就像模式每秒一样。
我怎么做这项工作。
答案 0 :(得分:1)
这是单元测试解决方案:
class TestCode extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FittedBox(
fit: BoxFit.scaleDown,
child: Container(
width: 200,
height: 100,
color: Colors.red,
child: FittedBox(
fit: BoxFit.scaleDown,
child: Container(
width: 100,
height: 100,
color: Colors.green,
),
),
),
);
}
}
:
server.js
const cron = require("node-cron");
const server = (module.exports = {
cronJob: null,
scheduledJob: function(pattern) {
server.cronJob = cron.schedule(pattern, () => {
server.run();
});
},
run: function() {
console.log("run called");
},
});
:
server.test.js
覆盖率100%的单元测试结果:
const server = require("./server");
const sinon = require("sinon");
const cron = require("node-cron");
const { expect } = require("chai");
describe("57208090", () => {
afterEach(() => {
sinon.restore();
});
describe("#scheduledJob", () => {
it("should schedule job", () => {
const pattern = "* * * * * *";
const runStub = sinon.stub(server, "run");
const scheduleStub = sinon
.stub(cron, "schedule")
.yields()
.returns({});
server.scheduledJob(pattern);
sinon.assert.calledWith(scheduleStub, pattern, sinon.match.func);
sinon.assert.calledOnce(runStub);
expect(server.cronJob).to.be.eql({});
});
});
describe("#run", () => {
it("should run server", () => {
const logSpy = sinon.spy(console, "log");
server.run();
sinon.assert.calledWith(logSpy, "run called");
});
});
});
您要求进行单元测试。如果您需要集成测试,请创建一个新帖子。
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57208090