Skip to content

Commit c363aeb

Browse files
committed
mocha beforeEach/afterEach can still take callbacks
1 parent 2c15bd8 commit c363aeb

3 files changed

Lines changed: 30 additions & 4 deletions

File tree

lib/cb-promise.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Used by mocha.js, for when we want a callback to pass to
2+
// a child function, but still want to return a Promise.
3+
module.exports = () => {
4+
let cb
5+
const p = new Promise((res, rej) => {
6+
cb = er => er ? rej(er) : res()
7+
})
8+
return [cb, p]
9+
}

lib/mocha.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -110,19 +110,23 @@ function after (name, fn, options) {
110110
suite.after.push([name, fn, options])
111111
}
112112

113+
const cbPromise = require('./cb-promise.js')
114+
113115
function moment (when, fn) {
114116
const t = tapStack[ tapStack.length - 1 ]
115117
// need function because 'this' tells us which tap object
116118
// has the tapMochaTest thing in its options object
117-
t[when](function (cb) {
119+
t[when](function () {
118120
if (!this.options.tapMochaTest)
119-
return cb()
121+
return
120122
const suite = suiteStack[ suiteStack.length - 1 ]
123+
124+
const [cb, p] = cbPromise()
121125
const ret = fn.call(this, cb)
122126
if (ret && ret.then)
123127
return ret
124-
else if (fn.length === 0)
125-
return cb()
128+
else if (fn.length !== 0)
129+
return p
126130
})
127131
}
128132

test/cb-promise.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const t = require('../')
2+
const cbPromise = require('../lib/cb-promise.js')
3+
t.test('promise resolved when cb called', async t => {
4+
const [cb, p] = cbPromise()
5+
cb()
6+
return p
7+
})
8+
t.test('promise rejects when cb failed', t => {
9+
const [cb, p] = cbPromise()
10+
const poop = new Error('poop')
11+
cb(poop)
12+
return t.rejects(p, poop)
13+
})

0 commit comments

Comments
 (0)