DEV Community

[Comment from a deleted post]
Collapse
 
jtenner profile image
jtenner

Also, choosing JavaScript as your coding language means that you need a testing framework. This is because unit testing isn't built into the language. This is okay. A few utility functions like assert() get the job done.

/**
 * The assert function verifies if a condition is truthy.
 *
 * @param {boolean} condition - The condition that indicates if the
 * assertion passes.
 * @param {string} description - The message describing the assertion.
 */
function assert(condition: boolean, description: string): void {
   if (!condition) throw new Error(description);
}

Another function I really like is the xor() function, because we can negate assertions using an exclusive or operation.

function xor(a: boolean, b: boolean): boolean {
  return (a && !b) || (!a && b);
}

And now, we can verify a contrapositive assertion.

const negated: boolean = true;
const condtion: boolean = /* some truthy assertion of application state. */;

// now perform the assertion
assert(xor(condition, negated), "This is a negated assertion.");

This example is obviously contrived, but a bunch of tiny little tools really help. You don't need a testing framework. You need responsibility.