Skip to content

Commit fd201e0

Browse files
joyeecheungMylesBorins
authored andcommitted
doc: add guides on writing tests involving promises
Mention `common.crashOnUnhandledRejection()` and wrapping the handlers in `common.mustCall()` or `common.mustNotCall()`. PR-URL: #20988 Reviewed-By: Vse Mozhet Byt <vsemozhetbyt@gmail.com> Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 4cd4420 commit fd201e0

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

doc/guides/writing-tests.md

+31
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,37 @@ countdown.dec();
223223
countdown.dec(); // The countdown callback will be invoked now.
224224
```
225225

226+
#### Testing promises
227+
228+
When writing tests involving promises, either make sure that the
229+
`onFulfilled` or the `onRejected` handler is wrapped in
230+
`common.mustCall()` or `common.mustNotCall()` accordingly, or
231+
call `common.crashOnUnhandledRejection()` in the top level of the
232+
test to make sure that unhandled rejections would result in a test
233+
failure. For example:
234+
235+
```javascript
236+
const common = require('../common');
237+
const assert = require('assert');
238+
const fs = require('fs').promises;
239+
240+
// Use `common.crashOnUnhandledRejection()` to make sure unhandled rejections
241+
// will fail the test.
242+
common.crashOnUnhandledRejection();
243+
244+
// Or, wrap the `onRejected` handler in `common.mustNotCall()`.
245+
fs.writeFile('test-file', 'test').catch(common.mustNotCall());
246+
247+
// Or, wrap the `onFulfilled` handler in `common.mustCall()`.
248+
// If there are assertions in the `onFulfilled` handler, wrap
249+
// the next `onRejected` handler in `common.mustNotCall()`
250+
// to handle potential failures.
251+
fs.readFile('test-file').then(
252+
common.mustCall(
253+
(content) => assert.strictEqual(content.toString(), 'test2')
254+
))
255+
.catch(common.mustNotCall());
256+
```
226257

227258
### Flags
228259

0 commit comments

Comments
 (0)