Ani*_*nil 5 javascript unit-testing mocha.js node.js sinon
我需要使用 node-cron 调用一个函数,并想为此编写一个单元测试用例。单元测试用例应该能够测试函数是否正在根据模式进行调用。
下面是我的代码
const server = (module.exports = {
cronJob: null,
scheduledJob: function(pattern) {
server.cronJob = cron.schedule(pattern, () => {
server.run();
});
},
run: function() {
console.log("run called");
},
});
Run Code Online (Sandbox Code Playgroud)
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);
});
});
Run Code Online (Sandbox Code Playgroud)
两个问题:
除了setTimeout我必须等待 3 秒的选项之外,cron 作业将按照模式每秒运行 3 次。
此测试失败,错误为 server.cronjob.start is not a function。
我怎样才能使这项工作?
这是单元测试解决方案:
\n\nserver.js:
const cron = require("node-cron");\n\nconst server = (module.exports = {\n cronJob: null,\n scheduledJob: function(pattern) {\n server.cronJob = cron.schedule(pattern, () => {\n server.run();\n });\n },\n run: function() {\n console.log("run called");\n },\n});\nRun Code Online (Sandbox Code Playgroud)\n\nserver.test.js:
const server = require("./server");\nconst sinon = require("sinon");\nconst cron = require("node-cron");\nconst { expect } = require("chai");\n\ndescribe("57208090", () => {\n afterEach(() => {\n sinon.restore();\n });\n describe("#scheduledJob", () => {\n it("should schedule job", () => {\n const pattern = "* * * * * *";\n const runStub = sinon.stub(server, "run");\n const scheduleStub = sinon\n .stub(cron, "schedule")\n .yields()\n .returns({});\n server.scheduledJob(pattern);\n sinon.assert.calledWith(scheduleStub, pattern, sinon.match.func);\n sinon.assert.calledOnce(runStub);\n expect(server.cronJob).to.be.eql({});\n });\n });\n\n describe("#run", () => {\n it("should run server", () => {\n const logSpy = sinon.spy(console, "log");\n server.run();\n sinon.assert.calledWith(logSpy, "run called");\n });\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n100%覆盖率的单元测试结果:
\n\n 57208090\n #scheduledJob\n \xe2\x9c\x93 should schedule job\n #run\nrun called\n \xe2\x9c\x93 should run server\n\n\n 2 passing (12ms)\n\n----------------|----------|----------|----------|----------|-------------------|\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |\n----------------|----------|----------|----------|----------|-------------------|\nAll files | 100 | 100 | 100 | 100 | |\n server.js | 100 | 100 | 100 | 100 | |\n server.test.js | 100 | 100 | 100 | 100 | |\n----------------|----------|----------|----------|----------|-------------------|\nRun Code Online (Sandbox Code Playgroud)\n\n您要求进行单元测试。如果您需要集成测试,请创建一个新帖子。
\n\n源代码:https ://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57208090
\n| 归档时间: |
|
| 查看次数: |
3060 次 |
| 最近记录: |