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);
});
});
2つの質問:
setTimeout
どのオプションを除いて、パターンが毎秒のようにcronジョブが3回実行されるように、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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加