assert: improve assert.fail() API · nodejs/node@4917d8c

3 files changed

lines changed

Original file line numberDiff line numberDiff line change

@@ -194,14 +194,15 @@ If the values are not equal, an `AssertionError` is thrown with a `message`

194194

property set equal to the value of the `message` parameter. If the `message`

195195

parameter is undefined, a default error message is assigned.

196196
197+

## assert.fail(message)

197198

## assert.fail(actual, expected[, message[, operator[, stackStartFunction]]])

198199

<!-- YAML

199200

added: v0.1.21

200201

-->

201202

* `actual` {any}

202203

* `expected` {any}

203204

* `message` {any}

204-

* `operator` {string}

205+

* `operator` {string} (default: '!=')

205206

* `stackStartFunction` {function} (default: `assert.fail`)

206207
207208

Throws an `AssertionError`. If `message` is falsy, the error message is set as

@@ -221,6 +222,12 @@ assert.fail(1, 2, 'fail');

221222
222223

assert.fail(1, 2, 'whoops', '>');

223224

// AssertionError: whoops

225+
226+

assert.fail('boom');

227+

// AssertionError: boom

228+
229+

assert.fail('a', 'b');

230+

// AssertionError: 'a' != 'b'

224231

```

225232
226233

Example use of `stackStartFunction` for truncating the exception's stacktrace:

Original file line numberDiff line numberDiff line change

@@ -77,6 +77,10 @@ function getMessage(self) {

7777

// display purposes.

7878
7979

function fail(actual, expected, message, operator, stackStartFunction) {

80+

if (arguments.length === 1)

81+

message = actual;

82+

if (arguments.length === 2)

83+

operator = '!=';

8084

throw new assert.AssertionError({

8185

message: message,

8286

actual: actual,

Original file line numberDiff line numberDiff line change

@@ -3,6 +3,36 @@

33

require('../common');

44

const assert = require('assert');

55
6+

// no args

7+

assert.throws(

8+

() => { assert.fail(); },

9+

/^AssertionError: undefined undefined undefined$/

10+

);

11+
12+

// one arg = message

13+

assert.throws(

14+

() => { assert.fail('custom message'); },

15+

/^AssertionError: custom message$/

16+

);

17+
18+

// two args only, operator defaults to '!='

19+

assert.throws(

20+

() => { assert.fail('first', 'second'); },

21+

/^AssertionError: 'first' != 'second'$/

22+

);

23+
24+

// three args

25+

assert.throws(

26+

() => { assert.fail('ignored', 'ignored', 'another custom message'); },

27+

/^AssertionError: another custom message$/

28+

);

29+
30+

// no third arg (but a fourth arg)

31+

assert.throws(

32+

() => { assert.fail('first', 'second', undefined, 'operator'); },

33+

/^AssertionError: 'first' operator 'second'$/

34+

);

35+
636

// The stackFrameFunction should exclude the foo frame

737

assert.throws(

838

function foo() { assert.fail('first', 'second', 'message', '!==', foo); },