How to use assert

Comprehensive assert code examples:

How to use assert.doesNotMatch:

1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
    }
  );
  assert.match('I will pass', /pass$/);
}


// Multiple assert.doesNotMatch() tests.
{
  assert.throws(
    () => assert.doesNotMatch(/abc/, 'string'),
    {

How to use assert.default:

52
53
54
55
56
57
58
59
60
61
for (const bucketEntry of result.Contents || []) {
  if (bucketEntry.Size === 0) {
    log.error(new Error(`Got empty file: "${bucketEntry.Key}"`));
    continue;
  }
  assert_1.default.ok(bucketEntry.Key);
  const matches = bucketEntry.Key.match(/([^/]+).json$/);
  if (matches === null) {
    log.error(new Error(`Got weird filename in manifest listing: "${bucketEntry.Key}"`));
    continue;

How to use assert.match:

44
45
46
47
48
49
50
51
52
53
describe('format', () => {
  formats.forEach((value) => {
    it(`should produce an image with format ${value}`, async () => {
      subject = new iiif.Processor(`${base}/full/full/0/default.${value}`, streamResolver);
      const result = await subject.execute();
      assert.match(result.contentType, /^image\//);
    });
  });
});

How to use assert.strict:

91
92
93
94
95
96
97
98
99
100
    var req = basicRequest;
    req.headers.authorization = '45678945612346gyzergczergczergf';

    parser(req, res, function (error) {
        assert.ok(error instanceof errors.InvalidCredentialsError, 'Must raise an InvalidCredentialsError');
        assert.strict(error.message, 'missing credentials', 'Must raise an error with message missing credentials');
        done();
    });
}),
it('x-bm-date is used in priority to date', (done) => {

How to use assert.AssertionError:

269
270
271
272
273
274
275
276
277
278
279
280
281
// assert module must conform to the following interface.


var assert = module.exports = ok;


// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
//                             actual: actual,
//                             expected: expected })


assert.AssertionError = function AssertionError(options) {

How to use assert.throwsAsync:

396
397
398
399
400
401
402
403
404
		nonAlltime: {score: 0, totalCorrectAnswers: 0, totalPoints: 0},
		cycle: {score: 0, totalCorrectAnswers: 0, totalPoints: 0},
	});
}

await assert.throwsAsync(async () => trivia.mergeAlts('annika', 'heartofetheria'));

await trivia.requestAltMerge('annika', 'somerandomreg');
await trivia.requestAltMerge('heartofetheria', 'somerandomreg');

How to use assert.notDeepStrictEqual:

11
12
13
14
15
16
17
18
19
20
    Helpers.convertToFixed(expected, fractionDigits),
    message,
  );
}
assertNotDeepEqualWithTolerance(actual, expected, fractionDigits = 2, message) {
  assert.notDeepStrictEqual(
    Helpers.convertToFixed(actual, fractionDigits),
    Helpers.convertToFixed(expected, fractionDigits),
    message,
  );

How to use assert.doesNotThrowAsync:

404
405
406
407
408
409
410
411
412
413
	await trivia.requestAltMerge('heartofetheria', 'somerandomreg');

	await assert.throwsAsync(async () => trivia.mergeAlts('annika', 'heartofetheria'));

	await trivia.requestAltMerge('annika', 'heartofetheria');
	await assert.doesNotThrowAsync(async () => trivia.mergeAlts('annika', 'heartofetheria'));
});

it('should correctly merge alts', async () => {
	await trivia.database.updateLeaderboardForUser('annika', {

How to use assert.doesNotReject:

117
118
119
120
121
122
123
124
125

it('should transpile dependencies', async function() {
  const antd = porter.packet.find({ name: 'antd' });
  const style = antd.files['lib/style/default.less'];
  assert.ok(style);
  await assert.doesNotReject(async function() {
    await style.obtain();
  });
});

How to use assert.notStrictEqual:

188
189
190
191
192
193
194
195
196
197
  })
)
  .sort()
  .pop()

assert.notStrictEqual(parentPath, undefined, `missing parent of ${id}`)

parentPath = parentPath.slice(1) // remove leading slash

// TODO remove when this has been done before the export

How to use assert.notDeepEqual:

23
24
25
26
27
28
29
30
31
32
});

it('dangles off the parsed ast from a .js file', () => {
  precinct(read('amd.js'));
  assert.ok(precinct.ast);
  assert.notDeepEqual(precinct.ast, ast);
});

it('dangles off the parsed ast from a scss detective', () => {
  precinct(read('styles.scss'), { type: 'scss' });

How to use assert.rejects:

605
606
607
608
609
610
611
612
613
614
let deferred = new tester.Thenable();
let value = {};
deferred.reject(value);
deferred.resolve(123);
deferred.reject(12345);
await assert.rejects(async () => {
  await deferred;
}, err => {
  assert.strictEqual(err, value);
  return true;

How to use assert.notEqual:

184
185
186
187
188
189
190
191
192
193
});

it('returns the dependencies for the given filepath', () => {
  assert.notEqual(precinct.paperwork(path.join(__dirname, '/fixtures/es6.js')).length, 0);
  assert.notEqual(precinct.paperwork(path.join(__dirname, '/fixtures/styles.scss')).length, 0);
  assert.notEqual(precinct.paperwork(path.join(__dirname, '/fixtures/typescript.ts')).length, 0);
  assert.notEqual(precinct.paperwork(path.join(__dirname, '/fixtures/styles.css')).length, 0);
});

it('throws if the file cannot be found', () => {

How to use assert.fail:

1631
1632
1633
1634
1635
1636
1637
1638
1639
1640

When(
  'we make a Pending Transaction Information against txid {string} with format {string}',
  async function (txid, format) {
    if (format !== 'msgpack') {
      assert.fail('this SDK only supports format msgpack for this function');
    }
    await this.v2Client.pendingTransactionInformation(txid).do();
  }
);

How to use assert.doesNotThrow:

146
147
148
149
150
151
152
153
154
  assert.equal(cjs.includes('lib'), false);
  assert.equal(cjs.length, 0);
});

it('does not throw on unparsable .js files', () => {
  assert.doesNotThrow(() => {
    precinct(read('unparseable.js'));
  }, SyntaxError);
});

How to use assert.ifError:

80
81
82
83
84
85
86
87
88
89
  return err instanceof Error && err.message === 'test' && err.caught;
});

const p = require('./napi_child').spawnSync(
  process.execPath, [__filename, 'fatal', bindingPath]);
assert.ifError(p.error);
assert.ok(p.stderr.toString().includes(
  'FATAL ERROR: Error::ThrowFatalError This is a fatal error'));

assert.throws(() => binding.error.throwDefaultError(false),

How to use assert.throws:

407
408
409
410
411
412
413
414
415
416
      it(`when ${name}`, () => {
        if (setup) {
          setup();
        }
        const regex = new RegExp(errorMsg);
        assert.throws(() => { videoTrack.removeProcessor(getParam()); }, regex);
      });
    });
  });
});

How to use assert.deepEqual:

17
18
19
20
21
22
23
24
25
26
  const deps = precinct(ast);
  assert.equal(deps.length, 1);
});

it('dangles off a given ast', () => {
  assert.deepEqual(precinct.ast, ast);
});

it('dangles off the parsed ast from a .js file', () => {
  precinct(read('amd.js'));

How to use assert.deepStrictEqual:

4
5
6
7
8
9
10
11
12
13
14
// used in Audio/Video/Paragraphs sync
const TIME_DIFF_THRESHOLD = 0.3;


class AssertionHelper extends Helper {
  assertDeepEqualWithTolerance(actual, expected, fractionDigits = 2, message) {
    assert.deepStrictEqual(
      Helpers.convertToFixed(actual, fractionDigits),
      Helpers.convertToFixed(expected, fractionDigits),
      message,
    );

How to use assert.strictEqual:

693
694
695
696
697
698
699
700
701
702
dirMode: this._dirMode,
async validator() {
  await input.task
  if (expectedSize !== undefined) {
    // check that we read all the stream
    strictEqual(
      container.size,
      expectedSize,
      `transferred size ${container.size}, expected file size : ${expectedSize}`
    )

How to use assert.ok:

2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
    const info = await algosdk.waitForConfirmation(
      this.v2Client,
      fundingResponse.txId,
      1
    );
    assert.ok(info['confirmed-round'] > 0);
  }
);

Given(

How to use assert.equal:

24
25
26
27
28
29
30
31
32
33
34
   * @param {number} time1
   * @param {number} time2
   * @param {string} [message] for assertion
   */
  assertTimesInSync(time1, time2, message = '') {
    assert.equal(Math.abs(time1 - time2) < TIME_DIFF_THRESHOLD, true, message);
  }
}


module.exports = AssertionHelper;