Skip to content

Commit

Permalink
Add an assert util
Browse files Browse the repository at this point in the history
  • Loading branch information
bertdeblock committed Dec 15, 2021
1 parent dc2ecbc commit c3ccf47
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
37 changes: 37 additions & 0 deletions lib/debug/assert.js
@@ -0,0 +1,37 @@
'use strict';

/**
* Verify that a certain condition is met, or throw an error if otherwise.
*
* This is useful for communicating expectations in the code to other human
* readers as well as catching bugs that accidentally violate these expectations.
*
* ```js
* const { assert } = require('ember-cli/lib/debug');
*
* // Test for truthiness:
* assert('Must pass a string.', typeof str === 'string');
*
* // Fail unconditionally:
* assert('This code path should never run.');
* ```
*
* @method assert
* @param {String} description Describes the condition.
* This will become the message of the error thrown if the assertion fails.
* @param {Any} condition Must be truthy for the assertion to pass.
* If falsy, an error will be thrown.
*/
function assert(description, condition) {
if (!description) {
throw new Error('When calling `assert`, you must provide a description as the first argument.');
}

if (condition) {
return;
}

throw new Error(`ASSERTION FAILED: ${description}`);
}

module.exports = assert;
5 changes: 5 additions & 0 deletions lib/debug/index.js
@@ -0,0 +1,5 @@
'use strict';

module.exports = {
assert: require('./assert'),
};
44 changes: 44 additions & 0 deletions tests/unit/debug/assert-test.js
@@ -0,0 +1,44 @@
'use strict';

const { expect } = require('chai');
const { assert } = require('../../../lib/debug');

describe('assert', function () {
it('it throws when the description argument is missing', function () {
expect(() => {
assert();
}).to.throw('When calling `assert`, you must provide a description as the first argument.');

expect(() => {
assert('');
}).to.throw('When calling `assert`, you must provide a description as the first argument.');
});

it('it does nothing when the condition argument is truthy', function () {
expect(() => {
assert('description', 1);
}).to.not.throw();

expect(() => {
assert('description', {});
}).to.not.throw();

expect(() => {
assert('description', true);
}).to.not.throw();
});

it('it throws when the condition argument is falsy', function () {
expect(() => {
assert('description');
}).to.throw('ASSERTION FAILED: description');

expect(() => {
assert('description', null);
}).to.throw('ASSERTION FAILED: description');

expect(() => {
assert('description', false);
}).to.throw('ASSERTION FAILED: description');
});
});

0 comments on commit c3ccf47

Please sign in to comment.