Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert module use in nodejs?

Hello everyone I was reading node official documentation, and I've seen the "Assert" module, but don't understand its use, my conclutions up to now are that is like the (try--catch) of some languages, the examples on official documentation are not enough for me to understand the module, could you guys help me please?

like image 926
user3054736 Avatar asked Mar 19 '14 01:03

user3054736


Video Answer


2 Answers

These would be used for unit testing.

This module is used for writing unit tests for your applications, you can access it with require('assert'). http://nodejs.org/api/assert.html

The goal of a unit test is to test individual units of your code. For example, to test a function, you give it the input and know what output to expect. This will isolate that function so you can be sure there is not an error in other parts of your code.

like image 132
DFord Avatar answered Oct 20 '22 07:10

DFord


From the Node assert documentation:

The assert module provides a simple set of assertion tests that can be used to test invariants. The module is intended for internal use by Node.js, but can be used in application code via require('assert'). However, assert is not a testing framework, and is not intended to be used as a general purpose assertion library.

A simple use of the assert module would be to prevent a division by zero:

var noDivZero = (dividend, divisor) => {
  try {
    assert(divisor !== 0, 'DivisionByZeroException')
    return dividend / divisor
  } catch(e) {
    return e.message
  }
}

noDivZero(10, 0); // DivisionByZeroException
like image 3
gnerkus Avatar answered Oct 20 '22 06:10

gnerkus