Skip to content
This repository was archived by the owner on Mar 16, 2026. It is now read-only.
This repository was archived by the owner on Mar 16, 2026. It is now read-only.

assert #1051

@oldoc63

Description

@oldoc63

We already learned how to organize and automate tests using the Mocha test framework. To write the test themselves, we can use the assert.ok method provided by Node.js.
In programming, a test compares an expected outcome to an actual outcome. For example, we expect the outcome of the following code to be : a has a value of 3.

const a = 1 + 2;

To test the value saved to a with plain JavaScript, you would need to write a conditional statement comparing a to the expected result. Inside the statement, you would construct an error when the actual outcome does not match the expected.

if (a !== 3) {
throw 'Test failed! a is not a 3'
}

assert.ok() allows you to compare values and throw errors as needed using one function call. The small, human-readable format of the functions will help you make a more expressive test suite.
As a Node module, assert can be imported at the top of your files with:

const assert = require('assert');

assert.ok(a === 3):

In this case a === 3 evaluates to true, so no error is thrown.
If an argument passed to assert.ok() evaluates to false, an AssertionError in thrown. The error communicates to Mocha that a test has failed, and Mocha logs the error message to the console.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions