|
| 1 | +// mustCall is a function |
| 2 | +if (typeof mustCall !== 'function') { |
| 3 | + throw new Error('Expected a global mustCall function'); |
| 4 | +} |
| 5 | + |
| 6 | +// mustCall returns a [wrapper, called] tuple |
| 7 | +{ |
| 8 | + const [wrapper, called] = mustCall(); |
| 9 | + if (typeof wrapper !== 'function') { |
| 10 | + throw new Error('mustCall()[0] must be a function'); |
| 11 | + } |
| 12 | + if (!(called instanceof Promise)) { |
| 13 | + throw new Error('mustCall()[1] must be a Promise'); |
| 14 | + } |
| 15 | + wrapper(); |
| 16 | + await called; |
| 17 | +} |
| 18 | + |
| 19 | +// mustCall forwards arguments and return value |
| 20 | +{ |
| 21 | + const [wrapper, called] = mustCall((a, b) => a + b); |
| 22 | + const result = wrapper(2, 3); |
| 23 | + assert.strictEqual(result, 5); |
| 24 | + const resolvedValue = await called; |
| 25 | + assert.strictEqual(resolvedValue, 5); |
| 26 | +} |
| 27 | + |
| 28 | +// mustCall without fn argument works as a no-op wrapper |
| 29 | +{ |
| 30 | + const [wrapper, called] = mustCall(); |
| 31 | + const result = wrapper('ignored'); |
| 32 | + assert.strictEqual(result, undefined); |
| 33 | + await called; |
| 34 | +} |
| 35 | + |
| 36 | +// mustNotCall is a function |
| 37 | +if (typeof mustNotCall !== 'function') { |
| 38 | + throw new Error('Expected a global mustNotCall function'); |
| 39 | +} |
| 40 | + |
| 41 | +// mustNotCall returns a function |
| 42 | +{ |
| 43 | + const fn = mustNotCall(); |
| 44 | + if (typeof fn !== 'function') { |
| 45 | + throw new Error('mustNotCall() must return a function'); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// mustNotCall() throws when called |
| 50 | +{ |
| 51 | + const fn = mustNotCall(); |
| 52 | + let threw = false; |
| 53 | + try { |
| 54 | + fn(); |
| 55 | + } catch { |
| 56 | + threw = true; |
| 57 | + } |
| 58 | + if (!threw) throw new Error('mustNotCall() must throw when called'); |
| 59 | +} |
| 60 | + |
| 61 | +// mustNotCall(msg) includes the message |
| 62 | +{ |
| 63 | + const fn = mustNotCall('custom message'); |
| 64 | + let threw = false; |
| 65 | + try { |
| 66 | + fn(); |
| 67 | + } catch (error) { |
| 68 | + threw = true; |
| 69 | + if (!(error instanceof Error)) { |
| 70 | + throw new Error('mustNotCall must throw an Error instance'); |
| 71 | + } |
| 72 | + if (!error.message.includes('custom message')) { |
| 73 | + throw new Error(`mustNotCall error must include custom message, got: "${error.message}"`); |
| 74 | + } |
| 75 | + } |
| 76 | + if (!threw) throw new Error('mustNotCall(msg) must throw when called'); |
| 77 | +} |
0 commit comments