aboutsummaryrefslogtreecommitdiff
path: root/test/parallel/test-promises-warning-on-unhandled-rejection.js
blob: 0d6a74854217c8dafb5c7dfcc99aee167e225e6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Flags: --no-warnings --unhandled-rejections=warn
'use strict';

// Test that warnings are emitted when a Promise experiences an uncaught
// rejection, and then again if the rejection is handled later on.

const common = require('../common');
const assert = require('assert');

let b = 0;

process.on('warning', common.mustCall((warning) => {
  switch (b++) {
    case 0:
      // String rejection error displayed
      assert.strictEqual(warning.message, 'This was rejected');
      break;
    case 1:
      // Warning about rejection not being handled (will be next tick)
      assert.strictEqual(warning.name, 'UnhandledPromiseRejectionWarning');
      assert(
        /Unhandled promise rejection/.test(warning.message),
        'Expected warning message to contain "Unhandled promise rejection" ' +
        `but did not. Had "${warning.message}" instead.`
      );
      break;
    case 2:
      // Number rejection error displayed. Note it's been stringified
      assert.strictEqual(warning.message, '42');
      break;
    case 3:
      // Unhandled rejection warning (won't be handled next tick)
      assert.strictEqual(warning.name, 'UnhandledPromiseRejectionWarning');
      assert(
        /Unhandled promise rejection/.test(warning.message),
        'Expected warning message to contain "Unhandled promise rejection" ' +
        `but did not. Had "${warning.message}" instead.`
      );
      break;
    case 4:
      // Rejection handled asynchronously.
      assert.strictEqual(warning.name, 'PromiseRejectionHandledWarning');
      assert(/Promise rejection was handled asynchronously/
        .test(warning.message));
  }
}, 5));

const p = Promise.reject('This was rejected'); // Reject with a string
setImmediate(common.mustCall(() => p.catch(() => { })));
Promise.reject(42); // Reject with a number