# assert

### Assertions in Node.js

Imagine you're building a Lego tower. You want to make sure each block fits perfectly. Assert functions are like little inspectors that check if your building is as expected.

#### Basic Assertions

**`assert.ok(value)`**

Checks if `value` is truthy (not `null`, `undefined`, `0`, `''`, `false`).

Example:

```javascript
const isLoggedIn = true;
assert.ok(isLoggedIn); // Passes because `isLoggedIn` is truthy
```

**`assert.equal(actual, expected)`**

Checks if `actual` and `expected` are equal.

Example:

```javascript
const age = 25;
assert.equal(age, 25); // Passes because `age` is equal to 25
```

**`assert.notEqual(actual, expected)`**

Checks if `actual` and `expected` are not equal.

Example:

```javascript
const name = "Alice";
assert.notEqual(name, "Bob"); // Passes because `name` is not equal to "Bob"
```

#### More Complex Assertions

**`assert.deepEqual(actual, expected)`**

Checks if `actual` and `expected` are deeply equal, meaning they have the same value and structure.

Example:

```javascript
const obj1 = { name: "Alice", age: 25 };
const obj2 = { name: "Alice", age: 25 };
assert.deepEqual(obj1, obj2); // Passes because `obj1` and `obj2` are deeply equal
```

**`assert.throws(block, error)`**

Checks if `block` throws an error of type `error`.

Example:

```javascript
const divide = (a, b) => {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
};

assert.throws(() => divide(10, 0), Error); // Passes because `divide` throws an error when `b` is 0
```

#### Applications in Real World

Asserts are used extensively in unit testing, where they verify if functions or modules behave as expected.

Imagine a function that calculates the area of a rectangle. Using asserts, you can test if the area is calculated correctly for different input values.

```javascript
const calcArea = (width, height) => width * height;

// Unit test
it("Should calculate the area correctly", () => {
  assert.equal(calcArea(5, 10), 50);
  assert.equal(calcArea(2, 7), 14);
});
```

***

### Strict Assertion Mode

Imagine you're working on a toy assembly line in a toy factory. Your job is to check if the toys are made correctly.

**In Regular Mode (non-strict):**

* You're a bit lenient and don't pay much attention to the details.
* If a toy has a slight difference in color or shape, you don't worry about it.
* You're okay with the toys being "pretty close" to what they're supposed to be.

**In Strict Mode:**

* You're a perfectionist who wants every toy to be exactly as designed.
* You check every tiny detail, and even the smallest difference is unacceptable.
* You make sure that the toys are "100% identical" to the blueprints.

In Node.js, `assert` helps you check if certain conditions are true. By default, it uses the regular mode. To activate the strict mode, you use `assert.strict`.

**Example:**

**Regular Mode:**

```javascript
assert.deepEqual([1, 2, 3], [1.0, 2.0, 3.0]); // passes because it's "pretty close"
```

**Strict Mode:**

```javascript
assert.strict.deepEqual([1, 2, 3], [1.0, 2.0, 3.0]); // fails because they're not "100% identical"
```

**Error Messages:**

In regular mode, error messages for objects just show the objects, often cut off. In strict mode, it shows a diff to highlight the differences.

**Example:**

```javascript
assert.deepEqual([1, 2, [3]], [1, 2, [4]]);
```

**Regular Mode:**

```
AssertionError [ERR_ASSERTION]:
{
  0: 1,
  1: 2,
  2: [ 3 ]
} !=
{
  0: 1,
  1: 2,
  2: [ 4 ]
}
```

**Strict Mode:**

```
AssertionError [ERR_ASSERTION]:
Expected inputs to be strictly deep-equal:
+ actual - expected ... Lines skipped

  [
    1,
    2,
    [
...
      3
+     4
    ]
  ]

```

**Real-World Applications:**

Strict assertion mode is useful for ensuring the highest level of accuracy in your code. It can be used in:

* Validating data entered by users (e.g., in a registration form)
* Checking API responses for consistency and correctness
* Testing the behavior of third-party modules and libraries
* Debugging code by identifying subtle differences that might be causing issues

***

### Legacy Assertion Mode

Legacy assertion mode is an older way of writing assertions in Node.js. It uses the `==` operator to compare values for equality. The `==` operator compares values by value and type, so it can produce surprising results.

#### Functions in Legacy Assertion Mode

Legacy assertion mode affects the following functions in the `assert` module:

* `assert.deepEqual()`
* `assert.equal()`
* `assert.notDeepEqual()`
* `assert.notEqual()`

#### Using Legacy Assertion Mode

To use legacy assertion mode, you can import the `assert` module using either CommonJS or ES modules:

```javascript
// CommonJS
const assert = require("assert");

// ES modules
import assert from "assert";
```

#### Surprising Results in Legacy Assertion Mode

Legacy assertion mode can lead to unexpected results, especially when using `assert.deepEqual()`. For example:

```javascript
// WARNING: This will NOT throw an AssertionError!
assert.deepEqual(/a/gi, new Date());
```

This is because the `==` operator compares values by value and type, and in this case, both `/a/gi` and `new Date()` are objects with the same value (`"[object RegExp]"`).

#### Potential Applications

Legacy assertion mode is still used in some legacy codebases. However, it is not recommended to use it in new code. Instead, you should use the modern assertion mode, which uses the stricter `===` operator.

#### Real-World Examples

Here is an example of how to write an assertion in legacy assertion mode:

```javascript
assert.equal(1, "1"); // Passes in legacy assertion mode
```

Here is an example of how to write the same assertion in modern assertion mode:

```javascript
assert.strictEqual(1, "1"); // Fails in modern assertion mode
```

#### Recommendations

It is recommended to use the modern assertion mode whenever possible. Legacy assertion mode is deprecated and may be removed in a future version of Node.js.

***

**What is an Assertion?**

In programming, an assertion is a statement that you expect to be true at a specific point in your code. For example, you might have a function that calculates the area of a triangle, and you expect it to always return a positive number. You can write an assertion to check that this is the case.

**What is an AssertionError?**

An AssertionError is an error that is thrown when an assertion fails. This means that the condition you specified in your assertion was not met. For example, if you have a function that calculates the area of a triangle, and you expect it to always return a positive number, but it actually returns a negative number, then an AssertionError will be thrown.

**How to Throw an AssertionError**

You can throw an AssertionError using the `assert` module. The `assert` module provides a number of different functions for checking different conditions. If any of these conditions fail, an AssertionError will be thrown.

For example, to check that a value is not null, you can use the `assert.ok()` function:

```
const assert = require('assert');

assert.ok(value);
```

If `value` is null, then an AssertionError will be thrown.

**How to Handle Assertions**

You can handle assertions by catching the AssertionError error. For example:

```
try {
  assert.ok(value);
} catch (err) {
  if (err instanceof AssertionError) {
    // Handle the AssertionError
  } else {
    // Handle other errors
  }
}
```

**Real-World Applications**

Assertions can be used in a variety of real-world applications, such as:

* **Testing:** You can use assertions to test the correctness of your code. For example, you can write assertions to check that your functions return the correct values, or that your objects have the correct properties.
* **Debugging:** You can use assertions to help you debug your code. For example, you can add assertions to key points in your code to help you identify where errors are occurring.
* **Documentation:** You can use assertions to document the expected behavior of your code. This can help other developers to understand how your code is supposed to work.

**Conclusion**

Assertions are a powerful tool for ensuring the correctness and reliability of your code. By using assertions, you can catch errors early and prevent them from causing problems in your application.

***

**Introduction to assert.AssertionError**

In Node.js, an `AssertionError` is a special type of error that is thrown when an assertion fails. An assertion is a statement that is expected to be true in a given situation. If the assertion is not true, the `AssertionError` is thrown.

**Creating an AssertionError**

You can create an `AssertionError` directly using the `new` keyword. The following example creates an `AssertionError` with a custom message:

```javascript
const error = new assert.AssertionError({
  message: "My custom error message",
});
```

You can also pass additional options to the `AssertionError` constructor, such as the `actual` and `expected` values of the assertion. These values will be included in the error message.

```javascript
const error = new assert.AssertionError({
  message: "Expected value to be 10, but got 5",
  actual: 5,
  expected: 10,
});
```

**Properties of an AssertionError**

An `AssertionError` has the following properties:

* `message`: The error message.
* `name`: The error name, which is always `'AssertionError'`.
* `actual`: The actual value of the assertion.
* `expected`: The expected value of the assertion.
* `operator`: The operator that was used in the assertion, such as `'==='` or `'>='`.
* `generatedMessage`: A boolean value that indicates whether the error message was generated automatically or not.
* `code`: The error code, which is always `'ERR_ASSERTION'`.

**Throwing an AssertionError**

You can throw an `AssertionError` using the `assert` module. The `assert` module provides a number of methods that can be used to perform assertions. If any of these methods fail, an `AssertionError` is thrown.

For example, the following code throws an `AssertionError` if the value of `x` is not equal to 10:

```javascript
assert.strictEqual(x, 10);
```

**Handling an AssertionError**

When an `AssertionError` is thrown, you can handle it like any other error. You can catch the error using a `try/catch` block, or you can let it propagate up the call stack.

For example, the following code catches the `AssertionError` and logs the error message:

```javascript
try {
  assert.strictEqual(x, 10);
} catch (error) {
  if (error instanceof assert.AssertionError) {
    console.log(error.message);
  } else {
    throw error;
  }
}
```

**Real-World Applications**

`AssertionErrors` are commonly used in unit testing to verify that the expected behavior of a function or method is met. For example, the following test checks that the `add` function correctly adds two numbers:

```javascript
const assert = require("assert");

function add(x, y) {
  return x + y;
}

it("should add two numbers", () => {
  assert.strictEqual(add(1, 2), 3);
});
```

If the `add` function does not return the expected value, the test will fail and the `AssertionError` will be thrown.

**Conclusion**

`AssertionErrors` are a useful tool for verifying the expected behavior of your code. They can help you to identify and fix errors early on, before they can cause problems in your production code.

***

**Class: `assert.CallTracker`**

This class is used to track the calls to a function. It can be used to verify that a function was called the expected number of times, with the expected arguments, and in the expected order.

**Usage:**

Create a new `CallTracker` object and pass it the function you want to track:

```javascript
const assert = require("assert");
const callTracker = new assert.CallTracker(myFunction);
```

Now, every time you call `myFunction`, the call will be tracked by the `callTracker` object.

**Methods:**

* **getCalls()**: Returns an array of all the calls that have been made to the function. Each call is represented by an object with the following properties:
  * `args`: The arguments that were passed to the function.
  * `thisValue`: The value of `this` that was used when the function was called.
  * `returnValue`: The return value of the function.
* **assertCalled(n, ...args)**: Asserts that the function was called exactly `n` times with the specified arguments.
* **assertCalledWith(call)**: Asserts that the function was called at least once with the specified arguments.
* **assertCalledWithNew(call)**: Asserts that the function was called at least once with the specified constructor arguments.
* **assertCalledInOrder(calls)**: Asserts that the function was called in the specified order with the specified arguments.

**Example:**

The following example shows how to use the `CallTracker` class to track the calls to a function:

```javascript
function myFunction(a, b) {
  return a + b;
}

const assert = require("assert");
const callTracker = new assert.CallTracker(myFunction);

myFunction(1, 2);
myFunction(3, 4);

const calls = callTracker.getCalls();

assert.strictEqual(calls.length, 2);
assert.deepStrictEqual(calls[0].args, [1, 2]);
assert.deepStrictEqual(calls[1].args, [3, 4]);
```

**Real-World Applications:**

The `CallTracker` class can be used in a variety of real-world applications, such as:

* Testing: You can use the `CallTracker` class to verify that a function was called the expected number of times, with the expected arguments, and in the expected order.
* Debugging: You can use the `CallTracker` class to help debug your code by tracking the calls to a function and seeing what arguments were passed and what the return value was.
* Profiling: You can use the `CallTracker` class to profile your code and see how often a function is called and how long it takes to execute.

***

### CallTracker in Assert module

#### Introduction

In JavaScript testing, sometimes you need to verify that a function has been called a specific number of times. The `CallTracker` class in the `assert` module helps you do just that.

#### Creating a CallTracker

To start tracking function calls, create a `CallTracker` object:

```
const tracker = new assert.CallTracker();
```

#### Tracking Function Calls

Use the `calls()` method to track a function:

```
const callsfunc = tracker.calls(func, 1);
```

This line tells the tracker to expect the `func` function to be called exactly 1 time.

#### Verifying Function Calls

After tracking all the function calls, call `verify()` to check if the expected number of calls were made:

```
tracker.verify();
```

If all the tracked functions were called the expected number of times, `verify()` will be successful. Otherwise, it will throw an error.

#### Real-World Example

Let's test a simple function that increments a counter:

```
function incrementCounter() {
  counter++;
}
```

We want to make sure that this function is called twice in our test:

```
const tracker = new assert.CallTracker();

const callsIncrementCounter = tracker.calls(incrementCounter, 2);

incrementCounter();
incrementCounter();

tracker.verify();
```

If the `incrementCounter` function is called exactly twice, the test will pass without throwing an error.

#### Applications

`CallTracker` is useful in various scenarios:

* Verifying that event listeners are attached or removed as expected.
* Checking if database queries are executed the desired number of times.
* Ensuring that API requests are made within a specific limit.
* Testing the execution flow of asynchronous functions.

***

### `tracker.calls([fn][, exact])`

#### Simplified Explanation

The `tracker.calls` function helps you track how many times a function has been called.

You give it a function, and it returns a new function that you should use instead of the original function. The new function will keep track of how many times it's been called.

When you call the new function, the tracker will count how many times it's been called. You can then use the `tracker.verify()` function to check that the function has been called the exact number of times you expected.

#### Detailed Explanation

The `tracker.calls` function takes two arguments:

* `fn`: This is the function you want to track.
* `exact`: This is the optional number of times you expect the function to be called. If you don't provide this number, the default is 1.

The `tracker.calls` function returns a new function that wraps the original function. This new function will call the original function, but it will also keep track of how many times it's been called.

You can then use the `tracker.verify()` function to check that the function has been called the exact number of times you expected. If the function has not been called the expected number of times, `tracker.verify()` will throw an error.

#### Code Examples

Here is an example of how to use the `tracker.calls` function:

```javascript
const assert = require("assert");

// Create a call tracker.
const tracker = new assert.CallTracker();

// Get a wrapped function that tracks how many times it's been called.
const trackedFunction = tracker.calls(function () {});

// Call the tracked function several times.
trackedFunction();
trackedFunction();
trackedFunction();

// Verify that the function has been called the expected number of times.
tracker.verify();
```

In this example, we create a call tracker and then use the `tracker.calls` function to get a wrapped function that tracks how many times it's been called. We then call the wrapped function several times and finally use the `tracker.verify()` function to check that the function has been called the expected number of times.

#### Real-World Applications

The `tracker.calls` function can be used in a variety of real-world applications, such as:

* Testing: You can use the `tracker.calls` function to test that a function has been called the expected number of times.
* Debugging: You can use the `tracker.calls` function to debug code and find out why a function is not being called as expected.
* Performance tuning: You can use the `tracker.calls` function to identify performance bottlenecks by tracking how many times a function is being called.

***

#### `tracker.getCalls(fn)`

**Summary:** Gets all the calls made to a tracked function.

**Parameters:**

* `fn`: The tracked function for which to get the calls.

**Returns:** An array of objects, each representing a single call to the tracked function. Each object has the following properties:

* `thisArg`: The value of `this` when the function was called.
* `arguments`: An array of arguments passed to the function.

**Example:**

```javascript
const assert = require("assert");

const tracker = new assert.CallTracker();

function func() {}
const callsfunc = tracker.calls(func);
callsfunc(1, 2, 3);

assert.deepStrictEqual(tracker.getCalls(callsfunc), [
  { thisArg: undefined, arguments: [1, 2, 3] },
]);
```

**Simplified Explanation:**

* The `assert.CallTracker` class allows you to track calls to a function.
* `tracker.calls(func)` returns a function that tracks calls to `func`.
* `tracker.getCalls(callsfunc)` returns an array of all the calls made to the tracked function.
* Each call object contains information about the function call, such as the value of `this` and the arguments passed to the function.

**Real-World Applications:**

* Testing: To verify that a function was called with specific arguments and in a specific context.
* Debugging: To understand the flow of execution and identify any unexpected calls to a function.
* Mocking: To create a mock function that tracks calls and returns predefined values.

***

### `tracker.report()`

#### Description

The `tracker.report()` method of the `assert` module returns an array of objects containing information about the wrapper functions returned by \[`tracker.calls()`]\[].

#### Syntax

```typescript
tracker.report(): object[];
```

#### Parameters

This method does not take any parameters.

#### Return Value

The return value is an array of objects containing the following information:

* `message`: A string containing a message about the expected and actual number of times the function was called.
* `actual`: The actual number of times the function was called.
* `expected`: The expected number of times the function was called.
* `operator`: The name of the function that is wrapped.
* `stack`: A stack trace of the function.

#### Example

The following example shows how to use the `tracker.report()` method:

```javascript
const assert = require("assert");

// Creates call tracker.
const tracker = new assert.CallTracker();

function func() {}

// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func, 2);

// Returns an array containing information on callsfunc()
console.log(tracker.report());
// [
//  {
//    message: 'Expected the func function to be executed 2 time(s) but was
//    executed 0 time(s).',
//    actual: 0,
//    expected: 2,
//    operator: 'func',
//    stack: stack trace
//  }
// ]
```

#### Potential Applications

The `tracker.report()` method can be used to verify that a function was called the expected number of times. This can be useful for testing purposes or for debugging code.

***

**Tracker.reset**

The `reset` method of the `CallTracker` class in the `assert` module resets the calls of the call tracker. If a tracked function is passed as an argument, the calls will be reset for it. If no arguments are passed, all tracked functions will be reset.

**Here's a simplified explanation:**

The `CallTracker` class is used to track calls to a function. The `reset` method resets the tracked calls. This can be useful if you want to start tracking calls from the beginning again.

**Here's an example of how to use the `reset` method:**

```
const assert = require('assert');

const tracker = new assert.CallTracker();

function func() {}
const callsfunc = tracker.calls(func);

callsfunc();
// Tracker was called once
assert.strictEqual(tracker.getCalls(callsfunc).length, 1);

tracker.reset(callsfunc);
assert.strictEqual(tracker.getCalls(callsfunc).length, 0);
```

In this example, we create a `CallTracker` instance and track calls to the `func` function. After calling `func` once, we can see that the tracker has recorded the call using `getCalls`. Then, we reset the calls using `reset` and verify that the tracker is now empty using `getCalls`.

**Here are some potential applications of the `reset` method:**

* Resetting the tracker after each test case to ensure that the calls are tracked separately.
* Resetting the tracker when the tracked function is updated or replaced.
* Resetting the tracker when the tracked function is no longer needed to be tracked.

***

### `tracker.verify()`

#### Explanation

The `verify()` method of the CallTracker class checks if all the functions passed to the `calls()` method have been called the expected number of times. If a function has not been called the expected number of times, the `verify()` method will throw an error.

#### Simplified Example

**Here's a simplified example:**

```js
// Create a call tracker.
const tracker = new assert.CallTracker();

// Wrap a function with the call tracker to track its calls.
const trackedFunction = tracker.calls(myFunction);

// Call the tracked function twice.
trackedFunction();
trackedFunction();

// Verify that the tracked function was called twice.
tracker.verify(); // Will pass without throwing an error

// Verify that the tracked function was called three times.
tracker.verify(3); // Will throw an error because the function was only called twice
```

#### Code Implementation

**Here's a complete code implementation:**

```js
const assert = require("assert");

// Create a call tracker.
const tracker = new assert.CallTracker();

// Wrap a function with the call tracker.
const trackedFunction = tracker.calls(myFunction, 2);

// Call the tracked function.
trackedFunction();

try {
  // This will throw an error because the tracked function was only called once.
  tracker.verify();
} catch (error) {
  console.error(error); // Output: AssertionError: Expected 2 calls, but only saw 1.
}
```

#### Potential Applications

**Potential applications of the `verify()` method include:**

* Testing the expected behavior of asynchronous functions.
* Verifying that a function was called the correct number of times in a unit test.
* Ensuring that a function is not called more than a certain number of times.

***

#### assert(value\[, message])

The `assert(value[, message])` function in `assert` module is an alias of \[`assert.ok()`]\[].

It checks if the `value` is truthy. If it is not, an `AssertionError` is thrown. The optional `message` parameter can be used to provide a custom error message.

**Examples:**

```js
assert(true); // OK
assert(false, "This is not true"); // throws an AssertionError with message 'This is not true'
```

**Real World Applications:**

* **Testing:** The `assert` module can be used to write tests for your code. For example, you could use `assert` to check that the output of a function is what you expect it to be.
* **Validating Input:** The `assert` module can be used to validate input to your functions. For example, you could use `assert` to check that a function parameter is of the correct type.

**Potential Code Implementations:**

```js
// Example 1: Testing
function add(a, b) {
  return a + b;
}

assert.equal(add(1, 2), 3); // OK
assert.equal(add(1, 2), 4); // throws an AssertionError with message 'Expected 4, but got 3'

// Example 2: Validating Input
function validateInput(input) {
  assert.ok(input, "Input cannot be null or undefined");
  assert.equal(typeof input, "string", "Input must be a string");
}

validateInput("hello"); // OK
validateInput(null); // throws an AssertionError with message 'Input cannot be null or undefined'
```

***

**assert.deepEqual()**

**Usage:**

```
assert.deepEqual(actual, expected, [message]);
```

**Parameters:**

* `actual`: The actual value.
* `expected`: The expected value.
* `message`: (Optional) A custom error message.

**Description:**

`assert.deepEqual()` checks if two values are deeply equal.

**Deep Equality** means that the values have the same structure and all of their properties are deeply equal.

**For example:**

```
assert.deepEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true
assert.deepEqual([1, 2], [1, 2]); // true
```

**However, be careful when comparing objects with circular references:**

```
const obj1 = { a: 1 };
const obj2 = { a: obj1 };
obj1.b = obj2;

assert.deepEqual(obj1, obj2); // throws an error
```

**This is because `assert.deepEqual()` uses JavaScript's `==` operator, which does not handle circular references correctly.**

**Use `assert.deepStrictEqual()` instead:**

`assert.deepStrictEqual()` is a stricter version of `assert.deepEqual()`. It uses a recursive algorithm to compare values and handles circular references correctly.

```
assert.deepStrictEqual(obj1, obj2); // true
```

**Applications:**

`assert.deepEqual()` is useful for testing the expected output of a function. For example:

```
function add(a, b) {
  return a + b;
}

const actual = add(1, 2);
const expected = 3;

assert.deepEqual(actual, expected); // passes
```

**However, it's better practice to use `assert.deepStrictEqual()`.**

***

### Deep Equality

**What is Deep Equality?**

Deep equality means checking if two objects have the same values for all of their properties, and if those properties are also deeply equal.

**How does `assert.deepEqual()` work?**

`assert.deepEqual()` compares two objects by:

* Checking if their property values are equal.
* If the values are objects, checking if those objects are also deeply equal.

**How is it different from regular equality?**

Regular equality (==) only checks if the two objects are the same object, or if their values are equal. It does not check properties.

### Enumerability and Order

**What is enumerability?**

Enumerability means whether a property can be accessed using `for...in` loops. By default, properties are enumerable.

**What is object order?**

The order of properties in an object is not guaranteed.

**How does this affect `assert.deepEqual()`?**

`assert.deepEqual()` only compares enumerable properties. It also doesn't care about the order of properties.

### Types and Special Cases

**Primitive values:** Compared using the == operator. `NaN` is considered equal to itself.

**Objects:** Type tags must match. Only enumerable "own" properties are compared.

**Errors:** Names and messages are always compared, even if not enumerable.

**Object wrappers:** Compared both as objects and unwrapped values.

**Maps and Sets:** Keys and items are compared unordered.

**Circular references:** Recursion stops when both sides differ or encounter a circular reference.

**Prototypes:** Not tested.

### Examples

```javascript
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };

assert.deepEqual(obj1, obj2); // true
```

```javascript
const obj1 = { a: { b: 1 } };
const obj2 = { a: { b: 2 } };

assert.deepEqual(obj1, obj2); // false
```

```javascript
const obj1 = { a: { b: 1 } };
const obj2 = { a: { b: 1 } };

obj2.a.b = 2;

assert.deepEqual(obj1, obj2); // false
```

### Real-World Applications

**Testing:** Ensuring that objects have the expected values and relationships.

**Data manipulation:** Verifying that data has been transformed or modified as intended.

**Validation:** Checking that user inputs or server responses meet specific criteria.

**Serialization:** Comparing objects before and after serialization to ensure data integrity.

***

**assert.deepStrictEqual**

**Purpose:** Check if two values are deeply equal, meaning that they have the same structure and values at all levels.

**Parameters:**

* **actual:** The actual value being tested.
* **expected:** The expected value being compared to.
* **message**(optional): A custom error message to be included if the assertion fails.

**How it Works:**

Deep equality compares the actual and expected values recursively, checking each property and value at every level.

**Example:**

```javascript
// Objects
const actual = {
  name: "John",
  age: 30,
};
const expected = {
  name: "John",
  age: 30,
};
assert.deepStrictEqual(actual, expected); // Passes

// Arrays
const actualArray = [1, 2, 3];
const expectedArray = [1, 2, 3];
assert.deepStrictEqual(actualArray, expectedArray); // Passes
```

**Applications:**

* Testing the equality of complex objects or arrays.
* Verifying that a function's output matches the expected result.
* Ensuring that data is consistent across different systems or processes.

**Real-World Example:**

Consider a function that calculates the total price of items in a shopping cart:

```javascript
function calculateTotalPrice(cart) {
  let total = 0;
  for (const item of cart) {
    total += item.price;
  }
  return total;
}

const cart = [
  { name: "Apple", price: 1.5 },
  { name: "Banana", price: 2.0 },
  { name: "Orange", price: 2.5 },
];
const expectedTotal = 6.0;

const actualTotal = calculateTotalPrice(cart);
assert.deepStrictEqual(actualTotal, expectedTotal, "Total price should match");
```

If the `calculateTotalPrice` function is working correctly, this assertion will pass, indicating that the actual total calculated is equal to the expected total.

***

**DeepStrictEqual**

The `assert.deepStrictEqual()` method in Node.js is used to compare two objects and ensure that they are strictly equal, meaning that they have the same value and the same type.

**How does it work?**

* **Primitive values** (e.g., numbers, strings, booleans) are compared using the `Object.is()` method.
* **Objects** are compared based on their type tags (e.g., `[object Object]`) and their \[\[Prototype]] chains.
* **Enumerable "own" properties** are considered during the comparison.
* **`Error`** objects are compared by their names and messages.
* **`Symbol`** properties are also compared.
* **Object wrappers** (e.g., `new Number(1)`) are compared both as objects and as their unwrapped values.
* **`Map`** and `**Set`\*\* keys and items are compared unordered.
* **`WeakMap`** and **`WeakSet`** comparison does not rely on their values.
* **`RegExp`** lastIndex, flags, and source are always compared.

**Example:**

```
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };

assert.deepStrictEqual(obj1, obj2); // passes
```

**Real-world application:**

This method is useful for testing the equality of complex objects, such as database records or API responses. It ensures that the values and types match exactly.

**Potential pitfalls:**

* Different type tags can cause unexpected results (e.g., comparing a `Date` object to a `fakeDate` object with the same \[\[Prototype]]).
* Unwrapped numbers and strings can be equal but not strictly equal (e.g., `new Number(1)` and `new Number(2)`).
* Circular references can lead to infinite recursion and cause the comparison to fail.

**Additional methods:**

* `assert.deepEqual()` - Compares objects using a recursive algorithm that does not enforce strict equality.
* `assert.notDeepStrictEqual()` - Checks that two objects are not strictly equal.
* `assert.notDeepEqual()` - Checks that two objects are not recursively equal.

***

#### `assert.doesNotMatch(string, regexp[, message])`

* `string` is the input string you want to test
* `regexp` is the regular expression you want to check against
* `message` is an optional error message

This function checks if the `string` does not match the `regexp`. If it does, it throws an \[`AssertionError`]\[] with the `message` you provided. Here's a simple example:

```js
const assert = require("assert");

assert.doesNotMatch("I will pass", /fail/);
```

This will pass because the string "I will pass" does not match the regular expression /fail/. However, if we change the string to "I will fail":

```js
assert.doesNotMatch("I will fail", /fail/);
```

This will fail and throw an \[`AssertionError`]\[] because the string "I will fail" does match the regular expression /fail/.

#### Real-world example

One common use case for `assert.doesNotMatch` is to validate user input. For example, you could use it to make sure that a user's password does not contain any special characters:

```js
const assert = require("assert");

function validatePassword(password) {
  assert.doesNotMatch(password, /[^a-zA-Z0-9]/);
  // ...
}
```

This function will only allow passwords that contain letters or numbers. If a user tries to enter a password with a special character, the `assert.doesNotMatch` will throw an \[`AssertionError`]\[] and the function will fail.

#### Potential applications

Here are some potential applications for `assert.doesNotMatch`:

* Validating user input
* Checking for errors in your code
* Testing the output of your functions
* Writing unit tests for your applications

***

#### `assert.doesNotReject(asyncFn[, error][, message])`

* `asyncFn` {Function|Promise}
* `error` {RegExp|Function}
* `message` {string}

#### Explanation:

* `assert.doesNotReject` is a function used to assert that a function or promise does not reject with an error.
* The `asyncFn` parameter is the asynchronous function or promise that you want to test.
* The `error` parameter is optional and can be used to specify the type of error that you expect the function or promise to not reject with. It can be a `RegExp` object, a `Function`, or a `Class`.
* The `message` parameter is also optional and can be used to provide a custom error message if the assertion fails.

#### How to use:

* You can use `assert.doesNotReject` in the following way:

```javascript
assert.doesNotReject(async () => {
  // Your asynchronous code here
});
```

* If the `asyncFn` does not reject with an error, the assertion will pass and your code will continue to execute.
* If the `asyncFn` rejects with an error, the assertion will fail and the `message` parameter will be displayed.

#### Example:

* The following example shows how to use `assert.doesNotReject` to test an asynchronous function that returns a promise:

```javascript
const assert = require("assert");

const myAsyncFunction = async () => {
  return "Hello, world!";
};

assert.doesNotReject(myAsyncFunction);
```

* In this example, the `myAsyncFunction` does not reject with an error, so the assertion will pass.

#### Potential applications:

* `assert.doesNotReject` can be used in unit tests to assert that a function or promise does not reject with an error. This can be helpful for testing error handling code.
* `assert.doesNotReject` can also be used in production code to handle errors gracefully. For example, you could use `assert.doesNotReject` to handle errors that occur during asynchronous operations.

#### Improved/Simplified Code Snippet:

```javascript
// Example of a function that does not reject
const noRejectFunction = async () => {
  return "No rejection here";
};

// Example of a promise that does not reject
const noRejectPromise = Promise.resolve("No rejection here either");

// Test that the function does not reject, message will be displayed if it does
assert.doesNotReject(
  noRejectFunction,
  /No rejection/,
  "Function should not reject"
);

// Test that the promise does not reject, message will be displayed if it does
assert.doesNotReject(
  noRejectPromise,
  /No rejection/,
  "Promise should not reject"
);
```

#### Real-World Implementation:

Consider an API endpoint that retrieves data from a database and sends a response to the client. You could use `assert.doesNotReject` to ensure that the endpoint does not reject with an error, even if the database is unavailable or the data is corrupted. This helps to ensure that the endpoint remains responsive and available to clients, even in the event of errors.

```javascript
// API endpoint that retrieves data from a database
const getData = async (req, res) => {
  try {
    const data = await database.getData();
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: "Internal server error" });
  }
};

// Unit test for the getData endpoint
const testGetData = async () => {
  // Mock the database to simulate an error
  const mockDB = {
    getData: async () => {
      throw new Error("Database error");
    },
  };

  // Use assert.doesNotReject to ensure that the endpoint does not reject with an error
  await assert.doesNotReject(
    getData,
    /Database error/,
    "Endpoint should not reject with database error"
  );
};
```

In this example, the `assert.doesNotReject` assertion will fail because the `getData` function rejects with an error. This helps to identify potential issues with the endpoint's error handling and ensures that it remains responsive to clients even in the event of errors.

***

**assert.doesNotThrow()**

**Simplified Explanation:**

Imagine you have a function that you expect to run smoothly without causing any errors. With `assert.doesNotThrow()`, you can check if that's the case.

**Function Signature:**

```
assert.doesNotThrow(fn, [error], [message]);
```

**Parameters:**

* **fn:** The function you want to test.
* **error (optional):** An error type, regular expression, or validation function that describes the type of error you don't expect the function to throw.
* **message (optional):** A custom error message to append to the `AssertionError` if the function throws an error.

**Example:**

```js
const assert = require("assert");

// Function that should not throw an error
const safeFunction = () => {
  // Do something that won't throw
};

// Testing the function with assert.doesNotThrow()
assert.doesNotThrow(safeFunction); // Passes

// Function that throws an error
const dangerousFunction = () => {
  throw new Error("Something went wrong!");
};

// Testing the function with assert.doesNotThrow()
assert.doesNotThrow(dangerousFunction); // Throws AssertionError
```

**Real-World Applications:**

* **Testing API responses:** Verify that API calls don't fail with unexpected errors.
* **Ensuring database operations:** Check that database queries and updates don't throw exceptions.
* **Validating user input:** Confirm that user-provided data doesn't cause validation errors.

**Tips:**

* Use `assert.doesNotThrow()` to test functions that you expect to succeed.
* If an error is thrown, specify the expected error type in the `error` parameter to get a more specific error message.
* Add a custom message in the `message` parameter to provide additional context if the assertion fails.

***

**assert.equal()**

The `assert.equal()` function is used to test whether two values are equal.

**Syntax**

```
assert.equal(actual, expected[, message])
```

**Parameters**

* `actual`: The actual value.
* `expected`: The expected value.
* `message` (optional): A custom error message.

**Return Value**

The function does not return any value.

**Example**

```
const assert = require('assert');

assert.equal(1, 1); // OK
assert.equal(1, '1'); // OK
assert.equal(NaN, NaN); // OK

assert.equal(1, 2); // AssertionError: 1 == 2
assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); // AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
```

**Real-World Applications**

* Testing the output of a function.
* Validating user input.
* Comparing two objects or arrays.

**Potential Applications**

* Unit testing
* Data validation
* Object comparison

**Simplified Explanation**

The `assert.equal()` function checks if two values are equal. If they are equal, the function does nothing. If they are not equal, the function throws an error.

**In very plain English, like explaining to a child**

Imagine you have two boxes of candy. You want to check if they have the same number of candies. You can use the `assert.equal()` function to do this. If the boxes have the same number of candies, the function will say "OK". If they don't have the same number of candies, the function will say "AssertionError".

***

### `assert.fail([message])`

In JavaScript, the `assert` module provides a way to check if a condition is true. If the condition is false, the `assert` module will throw an `AssertionError`.

The `assert.fail()` method is a way to manually throw an `AssertionError`. This can be useful in cases where you want to check for a specific condition, and you want to throw an `AssertionError` if that condition is not met.

For example, the following code uses the `assert.fail()` method to check if a variable is equal to a specific value:

```javascript
const assert = require("assert");

// Check if the variable `x` is equal to 10.
assert.fail(x !== 10, "The variable `x` is not equal to 10.");
```

If the variable `x` is not equal to 10, the `assert.fail()` method will throw an `AssertionError` with the message "The variable `x` is not equal to 10.".

The `assert.fail()` method can also be used to throw an `AssertionError` without a message. For example:

```javascript
const assert = require("assert");

// Throw an `AssertionError` without a message.
assert.fail();
```

This will throw an `AssertionError` with the default message "Failed.".

The `assert.fail()` method can be a useful tool for checking for specific conditions in your code. It can help you to ensure that your code is working as expected.

Here are some real-world examples of how the `assert.fail()` method can be used:

* In a unit test, you can use the `assert.fail()` method to check for specific conditions in your code. This can help you to ensure that your code is working as expected.
* In a production environment, you can use the `assert.fail()` method to check for specific conditions that could cause your code to fail. This can help you to prevent your code from crashing.

The `assert.fail()` method is a powerful tool that can be used to check for specific conditions in your code. It can help you to ensure that your code is working as expected and prevent it from crashing.

***

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

#### Description

The **assert.fail()** method in Node.js is used to create an `AssertionError` exception and throw it. This method is generally used for failing assertions in a way that provides a custom error message and stack trace.

#### Parameters

* `actual`: The actual value that failed the assertion.
* `expected`: The expected value that the assertion failed against.
* `message`: An optional custom error message. If not provided, a default message will be generated based on the values of `actual` and `expected`.
* `operator`: An optional comparison operator to use in the error message. The default operator is `'!='`.
* `stackStartFn`: An optional function to use as the starting point for the stack trace. This function's stack frame and all frames above it will be removed from the stack trace.

#### Usage

To use the **assert.fail()** method, simply call it with the appropriate parameters. For example, the following code throws an `AssertionError` exception with a custom error message:

```javascript
assert.fail("a", "b", "Values are not equal");
```

This will throw the following error:

```
AssertionError [ERR_ASSERTION]: Values are not equal
```

You can also use the **assert.fail()** method to set custom properties on the `AssertionError` exception. For example, the following code sets the `actual` and `expected` properties on the exception:

```javascript
assert.fail("a", "b", { actual: "a", expected: "b" });
```

This will throw the following error:

```
AssertionError [ERR_ASSERTION]: { actual: 'a', expected: 'b' }
```

#### Real-World Applications

The **assert.fail()** method can be used in any situation where you need to create a custom `AssertionError` exception. This can be useful for providing more detailed error messages or for customizing the stack trace.

For example, you could use the **assert.fail()** method to create an `AssertionError` exception that includes the current filename and line number:

```javascript
assert.fail(__filename, __line, "Assertion failed");
```

This would throw the following error:

```
AssertionError [ERR_ASSERTION]: Assertion failed at /path/to/file.js:123
```

#### Potential Applications

* Testing: The **assert.fail()** method can be used to create custom error messages for failed assertions in unit tests.
* Debugging: The **assert.fail()** method can be used to create custom error messages and stack traces for debugging purposes.
* Error handling: The **assert.fail()** method can be used to create custom error messages and stack traces for error handling purposes.

***

**What is assert.ifError()?**

`assert.ifError()` is a function in Node.js that checks if a value is not `undefined` or `null`. If the value is not `undefined` or `null`, `assert.ifError()` throws the value as an error.

**Why use assert.ifError()?**

`assert.ifError()` is useful when testing the `error` argument in callbacks. This is because `assert.ifError()` will include all frames from the error passed to it in the stack trace, including the frames for `assert.ifError()` itself.

**How to use assert.ifError()?**

The syntax of `assert.ifError()` is:

```
assert.ifError(value)
```

where:

* `value` is the value to check for an error

**Example:**

```js
import assert from "node:assert/strict";

assert.ifError(null); // OK
assert.ifError(0); // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
assert.ifError("error"); // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
assert.ifError(new Error()); // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
```

**Real-world applications:**

`assert.ifError()` can be used to test the `error` argument in callbacks to ensure that it is not `undefined` or `null`. This can be useful in debugging code and in writing tests.

**Potential applications:**

* Testing the `error` argument in callbacks
* Writing tests
* Debugging code

***

### `assert.match(string, regexp[, message])`

#### Overview

This function checks if a given string matches a regular expression.

#### Parameters

* `string`: The string to check.
* `regexp`: The regular expression to match against.
* `message`: An optional error message to display if the assertion fails.

#### Usage

To use this function, you first need to create a regular expression object. You can do this using the `RegExp` constructor.

```javascript
const regexp = new RegExp("pattern");
```

Once you have a regular expression object, you can use it to check if a string matches the pattern.

```javascript
assert.match("string to check", regexp);
```

If the string matches the pattern, the function will return without doing anything. If the string does not match the pattern, the function will throw an `AssertionError`.

You can also provide a custom error message to be displayed if the assertion fails.

```javascript
assert.match("string to check", regexp, "Custom error message");
```

#### Real-World Example

This function can be used to validate user input. For example, you could use it to check if a user has entered a valid email address.

```javascript
const emailRegex = new RegExp(
  "^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$"
);

assert.match("user@example.com", emailRegex);
```

If the user enters a valid email address, the function will return without doing anything. If the user enters an invalid email address, the function will throw an `AssertionError` with the message "Invalid email address".

#### Potential Applications

This function can be used in any situation where you need to check if a string matches a particular pattern. Some common applications include:

* Validating user input
* Parsing data
* Searching for text
* Checking for errors

***

**assert.notDeepEqual**

The `assert.notDeepEqual()` function is used to test if two objects are not deeply equal. Two objects are deeply equal if they have the same properties, and the values of those properties are also deeply equal.

```javascript
const assert = require("assert");

const obj1 = {
  a: 1,
  b: {
    c: 2,
  },
};

const obj2 = {
  a: 1,
  b: {
    c: 2,
  },
};

assert.notDeepEqual(obj1, obj2); // false
```

In this example, the two objects are deeply equal, so the `assert.notDeepEqual()` function will throw an error.

```javascript
const obj3 = {
  a: 1,
  b: {
    c: 3,
  },
};

assert.notDeepEqual(obj1, obj3); // true
```

In this example, the two objects are not deeply equal, so the `assert.notDeepEqual()` function will not throw an error.

The `assert.notDeepEqual()` function can be used to test the equality of any two objects. It is a useful tool for debugging and testing code.

**Real World Applications**

The `assert.notDeepEqual()` function can be used in a variety of real world applications, such as:

* Testing the equality of two objects in a database query
* Testing the equality of two objects in a web application
* Testing the equality of two objects in a unit test

**Code Implementations**

Here is a complete code implementation of the `assert.notDeepEqual()` function:

```javascript
function assertNotDeepEqual(actual, expected, message) {
  if (deepEqual(actual, expected)) {
    throw new AssertionError({
      message: message || "Values are deeply equal",
      actual: actual,
      expected: expected,
    });
  }
}
```

Here is an example of how to use the `assert.notDeepEqual()` function:

```javascript
const assert = require("assert");

const obj1 = {
  a: 1,
  b: {
    c: 2,
  },
};

const obj2 = {
  a: 1,
  b: {
    c: 3,
  },
};

assert.notDeepEqual(obj1, obj2); // true
```

**Potential Applications**

The `assert.notDeepEqual()` function can be used in a variety of potential applications, such as:

* Testing the equality of two objects in a database query
* Testing the equality of two objects in a web application
* Testing the equality of two objects in a unit test

***

### `assert.notDeepStrictEqual(actual, expected[, message])`

Tests if two objects are not deeply strictly equal. Deep strict equality means that the objects have the same structure, and that all of their properties are deeply strictly equal.

**Parameters:**

* `actual`: The first object to compare.
* `expected`: The second object to compare.
* `message` (optional): A custom error message to use if the assertion fails.

**Returns:**

* Nothing.

**Throws:**

* `AssertionError` if the `actual` and `expected` objects are deeply strictly equal.

**Example:**

```javascript
const assert = require("assert");

assert.notDeepStrictEqual({ a: 1 }, { a: "1" }); // OK
```

In this example, the `assert.notDeepStrictEqual()` function is used to test if the two objects are not deeply strictly equal. The first object has a property `a` that is set to the number `1`, while the second object has a property `a` that is set to the string `'1'`. Because the two objects have different types for their `a` properties, they are not deeply strictly equal. Therefore, the assertion passes.

**Real-world applications:**

The `assert.notDeepStrictEqual()` function can be used to test if two objects are not deeply strictly equal. This can be useful in situations where you need to ensure that two objects have different structures or properties. For example, you could use the `assert.notDeepStrictEqual()` function to test if two objects have different schemas or if they contain different data.

**Additional notes:**

* The `assert.notDeepStrictEqual()` function is the opposite of the `assert.deepStrictEqual()` function.
* The `assert.notDeepStrictEqual()` function uses the same deep equality algorithm as the `assert.deepStrictEqual()` function.
* The `assert.notDeepStrictEqual()` function throws an `AssertionError` if the `actual` and `expected` objects are deeply strictly equal.

***

### `assert.notEqual(actual, expected[, message])`

**Syntax**:

* `actual`: Value to be tested against expected.
* `expected`: Value to compare against the actual value.
* `message`: Optional error message to display if the assertion fails.

**Description**:

**Strict Assertion Mode** (introduced in Node.js v12.10.0):

* This function is an alias of `assert.notStrictEqual()`, which performs a strict inequality comparison.
* It tests if `actual` is not strictly equal to `expected`.
* If they are not equal, the assertion passes, otherwise an `AssertionError` is thrown.

**Legacy Assertion Mode** (deprecated since Node.js v12.10.0):

* Tests if `actual` is not shallowly equal to `expected`.
* Shallow equality is done using the `!=` operator.
* `NaN` values are treated as equal in legacy mode.

**Example 1: Strict Mode**:

```javascript
assert.notEqual("foo", "bar"); // Passes (strict inequality)
assert.notEqual(1, "1"); // Fails (strict inequality)
```

**Example 2: Legacy Mode**:

```javascript
assert.notEqual(1, 2); // Passes (shallow inequality)
assert.notEqual(1, "1"); // Fails (shallow inequality, but legacy mode treats them as equal)
```

**Real-World Applications**:

* Validating input, such as checking that a user's password does not match their username.
* Enforcing uniqueness constraints in data structures or databases.
* Testing for specific error conditions or expected exceptions.

***

**assert.notStrictEqual(actual, expected\[, message])**

**Purpose:**

Checks if two values are not strictly equal, meaning they have different values and are not the same type.

**Parameters:**

* **actual:** The actual value to test.
* **expected:** The expected value to compare against.
* **message (optional):** A custom error message to display if the assertion fails.

**How it works:**

Javascript has a special function called `Object.is()` that determines if two values are strictly equal. This function considers values like `0` and `-0` as being different, and it also checks for data types. For example, `1` and `"1"` are not strictly equal because they have different data types.

The `assert.notStrictEqual()` function uses `Object.is()` to check if the `actual` and `expected` values are not strictly equal. If they are not equal, the function does nothing, and execution continues. However, if the values are strictly equal, the function throws an `AssertionError` exception.

**Real-world Examples:**

* **Example 1:** Checking if two numbers are not equal:

```js
const number1 = 1;
const number2 = 2;

assert.notStrictEqual(number1, number2); // Passes because the numbers are not equal

// Throws an AssertionError:
// AssertionError [ERR_ASSERTION]: Expected "number1" to be strictly unequal to:
// 1
assert.notStrictEqual(number1, number1);
```

* **Example 2:** Checking if two strings are not equal:

```js
const string1 = "Hello";
const string2 = "World";

assert.notStrictEqual(string1, string2); // Passes because the strings are not equal

// Throws an AssertionError:
// AssertionError [ERR_ASSERTION]: Expected "string1" to be strictly unequal to:
// "Hello"
assert.notStrictEqual(string1, string1);
```

* **Example 3:** Checking if two objects are not strictly equal:

```js
const object1 = { name: "Bob" };
const object2 = { name: "Alice" };

assert.notStrictEqual(object1, object2); // Passes because the objects are not equal

// Throws an AssertionError:
// AssertionError [ERR_ASSERTION]: Expected "object1" to be strictly unequal to:
// { name: 'Bob' }
assert.notStrictEqual(object1, object1);
```

**Potential Applications:**

The `assert.notStrictEqual()` function can be useful in unit testing, where you want to ensure that certain conditions or values are not met. For example, you might use it to test that a function returns a specific non-default value.

***

**assert.ok()**

The `assert.ok()` function in Node.js is used to test if a given value is truthy. A truthy value is a value that, when evaluated in a Boolean context, is considered true. In JavaScript, the following values are considered truthy:

* `true`
* Any non-zero number
* Any non-empty string
* Any non-`null` object

**Simplified Explanation:**

Imagine you have a value, let's call it `myValue`. You want to check if `myValue` is "true-like". If it is, you want to continue running your code. If it's not, you want to stop and report an error.

That's where `assert.ok()` comes in. It takes your `myValue` and checks if it's truthy. If it is, everything is good and your code continues running. If it's not, `assert.ok()` throws an error, letting you know that something's wrong.

**Real-World Example:**

Let's say you have a function that takes a parameter and expects it to be a truthy value. If it's not, the function throws an error. You can use `assert.ok()` to test this before calling the function, ensuring that you don't get unexpected errors.

**Code Example:**

```javascript
function doSomething(value) {
  if (!value) {
    throw new Error("Value must be truthy!");
  }

  // Do something...
}

let myValue = null;
assert.ok(myValue, "myValue must be truthy!"); // Throws an error

myValue = true;
assert.ok(myValue, "myValue must be truthy!"); // No error, everything is OK
```

**Potential Applications:**

* Checking user input for validity
* Ensuring that function parameters meet certain requirements
* Debugging code to find missing or invalid values
* Writing unit tests to verify the correctness of your code

***

**Simplified Explanation of `assert.rejects()`**

Imagine you have a friend who's making you a promise to do something, and you want to check if they'll really keep it.

**What `assert.rejects()` does:**

* Waits for your friend to finish their task (promise to complete).
* Checks if they didn't keep their promise (the promise is rejected).
* If they didn't, it tells you they broke their promise!

**How to use `assert.rejects()`:**

1. **Pass it the promise or function that makes the promise:** This is your friend's task.
2. **Optionally, pass in a description of the error you expect:** If you know what kind of error your friend might make, you can tell `assert.rejects()` to check for it.
3. **Optionally, pass in a custom error message:** If you want to give a more specific error message when your friend doesn't keep their promise, you can do that too.

**Real-World Example:**

Let's say you have a function called `getCoffee()` that you expect to throw an error if there's no coffee left. You can use `assert.rejects()` to check that:

```javascript
// Starbucks runs out of coffee!
assert.rejects(getCoffee(), Error, "No coffee left!");
```

**Potential Applications:**

* Testing functions that are expected to fail (e.g., validation checks).
* Verifying that promises are rejected as expected.
* Debugging code that handles rejection scenarios.

**Simplified Code Snippet:**

```javascript
// Promise version
await assert.rejects(Promise.reject("Error!"), Error);

// Function version
assert.rejects(async () => {
  throw "Error!";
}, Error);
```

***

### `assert.strictEqual(actual, expected[, message])`

#### Purpose

The `assert.strictEqual()` function in Node.js is used to test whether two values are strictly equal, meaning they have the same value and are of the same type.

#### Syntax

```typescript
assert.strictEqual(actual, expected[, message]);
```

#### Parameters

* `actual`: The actual value being tested.
* `expected`: The expected value that the actual value should be equal to.
* `message` (optional): An optional error message to be included in the error thrown if the assertion fails.

#### How it works

The `assert.strictEqual()` function uses the strict equality operator (`===`) to compare the `actual` and `expected` values. If the values are not strictly equal, the function throws an `AssertionError` exception with the specified error message (or a default message if no message is provided).

#### Example

```javascript
const assert = require("assert");

// Test if two numbers are strictly equal
assert.strictEqual(1, 1); // OK

// Test if two strings are strictly equal
assert.strictEqual("hello", "hello"); // OK

// Test if two objects are strictly equal (even if they have the same properties)
const obj1 = { a: 1 };
const obj2 = { a: 1 };
assert.strictEqual(obj1, obj2); // AssertionError: Expected inputs to be strictly equal:
// + actual - expected
//
// + { a: 1 }
// - { a: 1 }
```

#### Real-World Application

The `assert.strictEqual()` function can be used in unit tests to ensure that the expected output of a function or method matches the actual output. For example, the following test verifies that the `add()` function correctly adds two numbers:

```javascript
const assert = require("assert");

function add(a, b) {
  return a + b;
}

assert.strictEqual(add(1, 2), 3); // OK
```

***

**assert.throws(fn\[, error]\[, message])**

This function in Node.js is used to test if a function (`fn`) throws an error.

**How to use it:**

1. **`fn`**: This is the function you want to test. It should throw an error.
2. **`error`**: This is optional. It can be:
   * A regular expression that matches the error message.
   * A function that returns `true` if the error matches the expected error.
   * An error object that the thrown error should match.
3. **`message`**: This is also optional. It's a custom error message that will be added to the error thrown by the `AssertionError` if the `fn` call doesn't throw an error or if the error validation fails.

**Example:**

```javascript
// This function should throw an error
function divideByZero() {
  return 10 / 0;
}

// Test if the function throws an error
assert.throws(divideByZero);

// Test if the error message matches a regular expression
assert.throws(divideByZero, /Division by zero/);

// Test if the error is an instance of a specific error class
assert.throws(divideByZero, TypeError);
```

**Real-World Application:**

This function is useful when you want to ensure that a certain function or operation throws an error. For example, if you have a function that validates user input, you can use `assert.throws()` to test if it throws an error when invalid input is provided.

**Potential Applications:**

* Testing error handling in code.
* Validating input data.
* Ensuring that functions throw specific errors.
* Writing unit tests for error-prone code.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://a7246c5516ab4c80cdfe21ca2be3e40c.gitbook.io/nodejs-docs/assert.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
