我需要使用node-cron调用一个函数,并为此编写一个单元测试用例。单元测试用例应该能够测试该函数是否正在根据模式进行调用。
下面是我的代码
const server = (module.exports = {
cronJob: null,
scheduledJob: function(pattern) {
server.cronJob = cron.schedule(pattern, () => {
server.run();
});
},
run: function() {
console.log("run called");
},
});
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);
});
});
两个问题:
[setTimeout
以外,我必须等待3秒钟才能使cron作业每秒运行3次,就像模式每秒一样。
此测试失败,并出现错误server.cronjob.start不是函数。
我该如何进行这项工作?
这里是单元测试解决方案:
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
:
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");
});
});
});
单元测试结果覆盖率100%:
57208090
#scheduledJob
✓ should schedule job
#run
run called
✓ should run server
2 passing (12ms)
----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
server.js | 100 | 100 | 100 | 100 | |
server.test.js | 100 | 100 | 100 | 100 | |
----------------|----------|----------|----------|----------|-------------------|
您要求进行单元测试。如果您需要集成测试,请创建一个新帖子。
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57208090