In the following example, I've two functions doTask and doSubTask. Both are async, but due to some business need, I need to fire & forget doSubTask twice with different parameters
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
const doTask = async (taskId) => {
await wait(taskId)
doSubTask(taskId * 3)
doSubTask(taskId * 5)
console.log('end task :' + taskId)
}
const doSubTask = async (subTaskId) => {
await wait(subTaskId)
console.log('end subTask :' + subTaskId)
}
doTask(2000)
How can I write a test case for doTask, and assert that doSubTask has been called twice?
Here's a code sample, you can run it on runkit.com
require("@fatso83/mini-mocha").install()
const sinon = require("sinon@7.5.0")
const referee = require("@sinonjs/referee")
const chai = require('chai')
chai.use(require('sinon-chai'))
const expect = chai.expect
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
const doTask = async (taskId) => {
await wait(taskId)
doSubTask(taskId * 3)
doSubTask(taskId * 5)
console.log('end task :' + taskId)
}
const doSubTask = async (subTaskId) => {
await wait(subTaskId)
console.log('end subTask :' + subTaskId)
}
const app = {
doTask,
doSubTask,
}
describe("stub", function () {
it("doSubTask should be called twice", async function () {
const doSubTaskSpy = sinon.spy(app, 'doSubTask')
await doTask(2000)
expect(doSubTaskSpy).to.be.calledTwice()
})
})
Output from the above code is:
stub
end task :2000
❌ doSubTask should be called twice (Failed with: "expecte…e been called exactly twice, but it was called 0 times")
end subTask :6000
end subTask :10000