JavaScript AssertEquals Explained: Ensuring Equality in Testing

This article will delve into the details of assertEquals in JavaScript, example programs, and how it can be effectively used to write robust and error-free code.

One crucial aspect of testing is verifying that the expected output matches the actual output. To achieve this, developers often employ an assertion method known as assertEquals.

Knowingly, in the world of software development, testing is an integral part of ensuring the quality and reliability of our code.

Now let’s get into detail!

Is There an Assert in JavaScript?

While some programming languages provide an assert keyword or function built into the language, JavaScript does not have a native assert function.

However, various testing frameworks and libraries, such as Mocha, Jest, and Node.js’s built-in assert module, offer their own implementations of assertion functions.

These frameworks allow you to write expressive and structured tests that can assert values and perform other test-related operations.

What is assertequals?

In software development, assertEquals is a method or function commonly used in testing frameworks to compare expected and actual values.

It is typically used to verify that the output of a particular function or piece of code matches the expected result.

Syntax

assertEquals(expectedValue, actualValue, message);

Parameters

  • expectedValue and actualValue are the values you want to compare, and message is an optional parameter that allows you to provide a custom error message in case the assertion fails.

Return Value

If the values are equal, the function does nothing. However, if they differ, an error is thrown, indicating that the test has failed.

What Is Assert Used for in JavaScript?

In JavaScript, assertions are used to validate assumptions about the behavior and correctness of code. They help ensure that the expected conditions are met during runtime.

By asserting values, you can catch potential bugs and errors early on, reducing the chances of introducing issues into your codebase.

Assertions play a crucial role in unit testing, where they act as checkpoints to verify that your code functions as intended.

With assertions, you can confirm that the output of a function matches the expected result, making it easier to identify discrepancies and address them promptly.

Example Programs of javascript assertequals

Here are several example programs in JavaScript that use the assertEquals function, along with a brief explanation of each:

Example 1 – Comparing Numbers using assertequals

function assertEquals(actual, expected) {
  if (actual === expected) {
    console.log("Test passed!");
  } else {
    console.error(`Test failed! Expected ${expected}, but got ${actual}.`);
  }
}

assertEquals(4, 4); // Test passed!
assertEquals(44, 4); // Test failed! Expected 4, but got 44.

This example demonstrates how to compare two numbers using assertEquals. It checks if the actual value is equal to the expected value.

If the test passes, a success message is logged. Otherwise, an error message is logged, displaying the expected and actual values.

Output:

Test passed!
Test failed! Expected 4, but got 44.

Example 2 – Comparing Strings with assertequals of javascript

function assertEquals(actual, expected) {
  if (actual === expected) {
    console.log("Test passed!");
  } else {
    console.error(`Test failed! Expected "${expected}", but got "${actual}".`);
  }
}

assertEquals("Hello @itsourcecode", "Hello @itsourcecode"); // Test passed!
assertEquals("Hi @itsourcecode", "Hello @itsourcecode!"); // Test failed! Expected "Hello @itsourcecode!", but got "Hi @itsourcecode".

In this example, assertEquals is used to compare two strings. It follows the same pattern as before, logging a success message if the values match and an error message otherwise.

Output:

Test passed!
Test failed! Expected "Hello @itsourcecode!", but got "Hi @itsourcecode".

Example 3 – Comparing Arrays

function assertEquals(actual, expected) {
  if (JSON.stringify(actual) === JSON.stringify(expected)) {
    console.log("Test passed!");
  } else {
    console.error(`Test failed! Expected ${JSON.stringify(expected)}, but got ${JSON.stringify(actual)}.`);
  }
}

assertEquals([2, 4, 6], [2, 4, 6]); // Test passed!
assertEquals([2, 4, 6], [2, 6, 4]); // Test failed! Expected [1, 3, 2], but got [1, 2, 3].

This example showcases how to compare arrays using assertEquals. The arrays are first converted to strings using JSON.stringify, allowing for a direct comparison.

If the arrays match, a success message is logged; otherwise, an error message is logged.

Output:

Test passed!
Test failed! Expected [2,6,4], but got [2,4,6].

Example 4 – Comparing Objects

function assertEquals(actual, expected) {
  if (JSON.stringify(actual) === JSON.stringify(expected)) {
    console.log("Test passed!");
  } else {
    console.error(`Test failed! Expected ${JSON.stringify(expected)}, but got ${JSON.stringify(actual)}.`);
  }
}

assertEquals({ name: "May", age: 25 }, { name: "May", age: 25 }); // Test passed!
assertEquals({ name: "June", age: 25 }, { name: "Jane", age: 25 }); // Test failed! Expected {"name":"Jane","age":25}, but got {"name":"June","age":25}.

In this example, assertEquals is used to compare objects. The objects are converted to strings using JSON.stringify for a direct comparison.

If the objects match, a success message is logged; otherwise, an error message is logged.

These examples demonstrate how the assertEquals function can be used to perform basic unit testing in JavaScript, comparing different types of values.

Output:

Test passed!
Test failed! Expected {"name":"Jane","age":25}, but got {"name":"June","age":25}.

Anyway here are some of the functions you might want to learn and can help you:

Conclusion

In conclusion, assertEquals is a crucial tool in the arsenal of every JavaScript developer.

Here are the key takeaways of this topic:

  • The article discusses the importance of testing and the use of the assertEquals method in JavaScript for comparing expected and actual values.
  • JavaScript does not have a native assert function, but various testing frameworks and libraries provide their own implementations.
  • The assertEquals method compares expected and actual values and throws an error if they differ.
  • Assertions in JavaScript are used to validate assumptions and ensure code correctness, helping catch bugs early on.
  • Assertions play a crucial role in unit testing and act as checkpoints to verify code functionality.
  • The article provides example programs using assertEquals to compare numbers, strings, arrays, and objects.
  • The examples demonstrate the usage of assertEquals and showcase how it can be used for basic unit testing in JavaScript.

Leave a Comment