To read more articles in this series please visit myMaking a blog, sample code please visithere.

The purpose of the assert

Assert is usually used to verify code and to prevent it from running and throw an error if it fails.

The use of the assert

Example code: /lesson11/assert.js

Try the following code:

const assert = require('assert')

assert(2 > 1, 2 > '1')

assert(1 > 2, '1 > 2')
Copy the code

When the code runs to Assert (2 > 1, ‘2 > 1’), it does not throw an error because 2 > 1 is true.

When assert(1 > 2, ‘1 > 2’) is false, the following error is thrown:

AssertionError [ERR_ASSERTION]: 1 > 2 at Object.<anonymous> (C:\projects\nodejs-tutorial\lesson11\assert.js:5:1) at Module._compile (internal/modules/cjs/loader.js:734:30) at Object.Module._extensions.. js (internal/modules/cjs/loader.js:745:10) at Module.load (internal/modules/cjs/loader.js:626:32) at tryModuleLoad (internal/modules/cjs/loader.js:566:12) at Function.Module._load (internal/modules/cjs/loader.js:558:3) at Function.Module.runMain (internal/modules/cjs/loader.js:797:12) at executeUserCode (internal/bootstrap/node.js:526:15) at startMainThreadExecution (internal/bootstrap/node.js:439:3)Copy the code

An error is indicated at line 5 of \lesson11\assert.js, and error message 1 > 2 is thrown and the code is terminated.

How assert is used

You can usually use Assert at every stage of a module or function, or after function arguments, to ensure that your code is running correctly.

assert.deepStrictEqual

Assert. DeepStrictEqual (actual, Expected [, message]) is used to compare actual parameters to expected in depth, verifying not only whether they are equal, but also whether their members are equal.

Assert. deepStrictEqual is useful for verifying objects or arrays.

The comparison of assert.deepStrictEqual is equivalent to ===, that is, not only values must be equal, but values must also be of the same type.

The use of the assert. DeepStrictEqual

  1. Use assert.deepStrictEqual to compare objects:

The sample code: / lesson11 / assert. DeepStrictEqual. Object. Js

const assert = require('assert')

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

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

const obj3 = {
  a: 1,
  b: 2,
  children: {
    c: '3'
  }
}

assert.deepStrictEqual(obj1, obj2, 'obj1 ! == obj2')

assert.deepStrictEqual(obj1, obj3, 'obj1 ! == obj3')
Copy the code

The code throws an error: obj1! = = obj3.

  1. Compare arrays using assert.deepStrictEqual:

The sample code: / lesson11 / assert. DeepStrictEqual. Array. Js

const assert = require('assert')

const arr1 = [{
  a: 1,
  b: 2,
  children: [{
    c: 3
  }]
}]

const arr2 = [{
  a: 1,
  b: 2,
  children: [{
    c: 3
  }]
}]

const arr3 = [{
  a: 1,
  b: 2,
  children: [{
    c: '3'
  }]
}]

assert.deepStrictEqual(arr1, arr2, 'arr1 ! == arr2')

assert.deepStrictEqual(arr1, arr3, 'arr1 ! == arr3')
Copy the code

The code throws an error: arr1! = = arr3.