Reputation: 1638
I'm new to nodejs, I follow all the steps in the documentation. First I study and test the assert function of node, I just want to know what is the purpose of using assert? if no error there's no output, but if you have an error, there's an output saying AssertError etc.
I want to know, when and what is the purpose of using assert?
Upvotes: 7
Views: 6374
Reputation: 994
In any programming language errors are an issue. Whether by human error or poor design. The assert module in node.js is used to test the behavior of a function and reduce the creation of "buggy" code, this also promotes design thinking.
In most cases assertions are used in unit testing. This takes a unit of code, be it a function, method etc and runs multiple tests on it. These test the value that a function generates(actual) vs what we expect the function to provide.
An example of assertions:
"use strict";
//Run the code and change the values of x and y (to equal 42) to test the assert module.
const x = 18;
const y = 20;
//We have to import our assert module
var assert = require("assert");
//Calculates the anser to life (42)
var life = function(a,b){
return a + b;
};
//Overwrite the variable of result to equal the return.
result = life(x,y);
//Change the comments below to see the difference between the two values
assert.deepEqual(result, 42);
//assert.fail(result, 42, "", '<');
From a technical point of view, developers should write their tests before they start to write their code. This is a form of top-down development strategy, which allows developers to understand the functional requirements of the software. Therefore when writing your assertions you obtain the parameters you require and what results you expect. Thus making the logic the only hurdle.
Upvotes: 9
Reputation: 1450
Assert is used to write test suites for your apps. This way, you can easily test your applications to see if they work as expected and catch errors early in the development stage .
Upvotes: 1