NodeJS 断言的目的

Purpose of assert in NodeJS

我是 nodejs 的新手,我遵循文档中的所有步骤。首先我研究和测试了node的assert功能,我只是想知道使用assert的目的是什么?如果没有错误就没有输出,但是如果你有错误,就会有一个输出说 AssertError 等等

我想知道什么时候使用 assert 的目的是什么?

Assert 用于为您的应用编写测试套件。这样,您可以轻松地测试您的应用程序,看看它们是否按预期工作,并在开发阶段及早发现错误。

在任何编程语言中,错误都是一个问题。无论是人为错误还是设计不当。 node.js中的断言模块用于测试函数的行为,减少"buggy"代码的创建,这也促进了设计思维。

在大多数情况下,断言用于单元测试。这需要一个代码单元,可以是函数、方法等,并对其运行多个测试。这些测试函数生成的值(实际)与我们期望函数提供的值。

断言示例:

"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, "", '<');

从技术角度来看,开发人员应该在开始编写代码之前编写测试。这是一种自上而下的开发策略,可以让开发人员了解软件的功能需求。因此,在编写断言时,您会获得所需的参数和期望的结果。从而使逻辑成为唯一的障碍。