Here is my take:
- using
async/await - no additional chai modules needed
- avoiding the catch problem, @TheCrazyProgrammer pointed out above
A function with a promise delay that fails if a delay of 0 is specified:
const timeoutPromise = (time) => { return new Promise((resolve, reject) => { if (time === 0) reject({ 'message': 'invalid time 0' }) setTimeout(() => resolve('done', time)) }) } // β β β it('promise selftest', async () => { // positive test let r = await timeoutPromise(500) assert.equal(r, 'done') // negative test try { await timeoutPromise(0) // a failing assert here is a bad idea, since it would lead into the catch clauseβ¦ } catch (err) { // optional, check for specific error (or error.type, error. message to contain β¦) assert.deepEqual(err, { 'message': 'invalid time 0' }) return // this is important } assert.isOk(false, 'timeOut must throw') log('last') })
A positive test is pretty simple. An unexpected failure (simulation at 500β0 ) will automatically end the test, as rejected promises will increase.
A negative test uses the idea of ββtry-catch. However: a "complaint" of an unwanted pass occurs only after the catch clause (thus, it does not end in the catch () clause, causing further, but misleading errors.
For this strategy to work, you need to return the test from the catch clause. If you do not want to test anything, use another () -block.
Frank Nocke Jun 22 '18 at 11:15 2018-06-22 11:15
source share