Home > Article > Web Front-end > Sharing examples of using assert in node.js
Assertion is a programming term, expressed as some Boolean expression, the programmer believes that the expression value is true at a certain point in the program, assertion verification can be enabled and disabled at any time, so assertions can be enabled during testing And disable assertions when deploying. Likewise, once the program is running, end users can re-enable assertions if they encounter problems.
Use assertions to create code that is more stable, better quality, and less error-prone. When you need to interrupt the current operation when a value is FALSE, you can use assertions. [Unit Test] Must use assertions.
Node provides more than 10 assertion test functions for testing invariants. I have grouped these more than 10 functions in the article to facilitate understanding and memory.
[Tip] In this article, expected represents the expected value, actual represents the actual value, and message represents custom information
2. Determine whether the value is a true value
Judgement Whether the value is true or not, there are the following two assertion test functions
2.1 assert(value[, message])
This test function passes the assertion when [Boolean(value)] is [true] Test, otherwise it will throw [AssertionError]
const assert = require("assert"); assert("blue","第一个值为false时以我为错误信息抛出"); assert(true,"第一个值为false时以我为错误信息抛出");
Because [Boolean(value)] in the above code are all true, they all pass the assertion test
assert(false,"第一个值为false时以我为错误信息抛出"); // AssertionError [ERR_ASSERTION]: 第一个值为false时以我为错误信息抛出
In the above code, if value is false, then it will be thrown Outputs an [AssertionError] with a message attribute, where the value of the message attribute is equal to the value of the incoming message parameter. [If the message parameter is undefined, the default error message will be assigned].
assert(false); // AssertionError [ERR_ASSERTION]: false == true
Since the above code does not specify the [message] parameter, it throws the default error message [AssertionError]
2.2 assert.ok(value[, message])
assert.ok() has the same function as assert(), they both test whether [value] is true. And the usage is the same, so assert() can be regarded as the syntactic sugar of assert.ok()
const assert = require("assert"); assert.ok(true); assert.ok(1);
The above code [Boolean(value)] is all true, so all assertions pass, and the following assertions do not pass In each case, the default error messages are listed respectively
assert.ok(0); //AssertionError [ERR_ASSERTION]: 0 == true assert.ok(false); //AssertionError [ERR_ASSERTION]: false == true assert.ok(false,"自定义错误信息"); //AssertionError [ERR_ASSERTION]: 自定义错误信息
3. Judging that the expected value and the actual value are equal (==)
There are two test functions in this group, used to test expectations Whether the value is equal to the actual value, if equal, the assertion passes, otherwise [AssertionError] is thrown
3.1 assert.equal(actual, expected[, message])
assert.equal() is used For testing whether the expected value and the actual value are equal, [When the value type is used, the two values are compared to see if they are equal. When the expected value and the actual value are reference types, the comparison is worth citing]
assert.equal(1, 1); assert.equal("1", 1);
Above The code is a comparison of value types, indicating that equal() uses (==) internally instead of strict equality. I will summarize it later on strict equality (===)
assert.equal({},{},"AssertionError"); assert.equal(() => { }, () => { }, "AssertionError"); assert.equal([],[],'AssertionError');
All three expressions will throw an [AssertionError] object with the [message] attribute value of 'AssertionError', [so when the value is a reference type, equal() compares the value of the reference, so the values of the two reference types are not the same. It cannot be asserted through equal()】
const obj={}; assert.equal(obj,obj); // 断言通过
The above code compares the same object and the two value references are equal, so the assertion passes.
3.2 assert.deepEqual(actual, expected[, message])
It also tests whether the expected value and the actual value are equal. The method still used is (==), but it is different from equal. Yes, [when deepEqual() compares reference types, it does not compare the reference of the value, but the attribute value of the compared object]
const a = 'Blue', b = 'Pink'; assert.deepEqual(a,a,'actual unequal to expected'); // 断言通过 assert.deepEqual(a,b,'actual unequal to expected'); // AssertionError [ERR_ASSERTION]: actual unequal to expected
The above is a comparison of value types, and equal () There is no difference
const obj1 = { name: "foo", gender: "men" }, obj2 = { name: "foo", gender: "men" }, obj3 = { name: "bar", gender: "men" } assert.deepEqual(obj1, obj2, 'actual unequal to expected'); // 断言通过 assert.deepEqual(obj1, obj3, 'actual unequal to expected'); // AssertionError [ERR_ASSERTION]: actual unequal to expected
The above code is a comparison of reference types. It can be seen that [deepEqual()] compares attribute values, not references. This is different from equal().
【Notice! ! 】deepEqual() only tests its own enumerable properties, and does not test the object's prototype, connector, or non-enumerable properties (use assert.deepStrictEqual() in these cases, which will be summarized later)
const son1 = Object.create(obj1), son2 = Object.create(obj2); son1.name="Summer"; son2.name="Summer"; assert.deepEqual(son1,son2,"actual unequal to expected"); // 断言通过
In the above code, son1 and son2 inherit from two different objects respectively, both of which have the attribute named "Summer". The final result is passed, indicating that [deepEqual() does not test the prototype of the object]
const ena = {}, enb = {}; Object.defineProperties(ena,{ name:{ value:"Blue" }, hobby:{ value:"foo", enumerable:false //可枚举性设置为false } }); Object.defineProperties(enb,{ name:{ value:"Blue" }, hobby:{ value:"bar", enumerable:false //可枚举性设置为false } }) assert.deepEqual(ena,enb,"actual unequal to expected") //ok,actual equal to expected
In the above code, ena and enb are used for the same enumerable attribute [name], and have non-enumerable attributes [hobby] with different values, indicating that [deepEqual() does not test the non-enumerable attributes of the object]
4. Determine whether the expected value and the actual value are congruent (===)
This set of test functions is used to determine whether the expected value and the actual value are equal in depth. The internal use is (===) , so the prototype of the object will also be compared, and the value type is also the scope of comparison. This set also has two test functions.
4.1 assert.deepStrictEqual(actual, expected[, message])
Since congruence (===) is used internally, the prototype of the object will also be included in the comparison range
const obj1 = { name: "foo", gender: "men" }, obj2 = { name: "bar", gender: "men" } const son1 = Object.create(obj1), son2 = Object.create(obj2); son1.name = "Summer"; son2.name = "Summer"; assert.deepEqual(son1, son2, "actual unequal to expected"); //断言通过 assert.deepStrictEqual(son1, son2, "actual unequal to expected") //AssertionError [ERR_ASSERTION]: actual unequal to expected
The above code uses deepEqual() and deepStrictEqual() for assertion testing. son1 and son2 inherit two different objects respectively, but have the same attribute values. It can be seen that [deepEqual() does not consider the prototype of the object, deepStrictEqual() includes the prototype object as a comparison object]
4.2 assert.strictEqual(actual, expected[, message])
strictEqual()是equal()的加强,考虑了数据类型;如果actual === expected,则断言通过,否则抛出AssertionError,message?message:默认错误信息。
assert.strictEqual(1, 2); // 抛出 AssertionError: 1 === 2 assert.strictEqual(1, 1); // 测试通过。 assert.strictEqual(1, '1'); // 抛出 AssertionError: 1 === '1' assert.equal(1, '1'); // 测试通过。
【提示!!】对引用类型还是永远通不过【strictEqual()】断言测试
五. 判断预期值和实际值不相等(!=)
上面总结到了判断预期值和实际值相等,这儿总结一下判断预期值和实际值不想等的两个测试函数,实际上就是上面 (三) 的逆运算。
5.1 assert.notEqual(actual, expected[, message])
【notEqual()】为 【equal() 】的逆运算,如果 actual!= expected 则断言通过,同样对于值类型是单纯对值进行比较,对应引用类型比较的是值得引用
assert.notEqual("1", "2"); // 断言通过 assert.notEqual("1", 2); // 断言通过 assert.notEqual("1", 1); // AssertionError [ERR_ASSERTION]: '1' != 1
上面代码是对值类型进行的比较,第三个表达式的默认信息可以看出内部使用的是(!=)
assert.notEqual({ a: "foo" }, { a: "foo" }); assert.notEqual(() => { }, () => { }); assert.notEqual([], []);
上面的代码是对引用类型进行的断言测试,【notEqual() 】对于两个对象的测试通过是一个【恒成立】的结果。
5.2 assert.notDeepEqual(actual, expected[, message])
【notDeepEqual() 】为 【deepEqual() 】的逆运算,如果 actual!= expected 则断言通过,不同于notEqual()的是对于引用类型是对值进行判断,不比对原型、不可枚举属性,只比对自有可枚举属性,断言通过。
const obj1 = { a: "foo" }, obj2 = { b: "bar" }, obj3 = Object.create(obj1); assert.notDeepEqual(obj1,obj1,'actual equal to expected'); // AssertionError [ERR_ASSERTION]: actual equal to expected assert.notDeepEqual(obj1,obj2,'actual equal to expected'); // 断言通过 assert.notDeepEqual(obj1,obj3,'actual equal to expected'); // 断言通过
上面代码中最后一个表达式断言通过,说明【不比对原型、不可枚举属性,只比对自有可枚举属性】
【注意!!】与notEqual的区别,也就是deepEqual和equal的区别,在引用数据类型的时候,deepEqual是比较的值而非引用,equal对比的是引用,所以引用类型在equal的时候是永远无法通过断言测试的,以此类推,引用类型在notEqual时是永远否可以通过断言测试的。
六. 判断预期值和实际值严格不相等(!==)
上面总结到了判断预期值和实际值严格相等,这儿总结一下判断预期值和实际值严格不相等的两个测试函数,实际上就是上面 (四) 的逆运算
6.1 assert.notStrictEqual(actual, expected[, message])
如果actual与expected不 !== 则断言通过, 与 assert.deepStrictEqual() 相反
assert.notStrictEqual("1", 1); // 断言通过 assert.notStrictEqual("1", "1"); // AssertionError [ERR_ASSERTION]: '1' !== '1'
上面代码是对值类型进行的断言测试,可以看出【notStrictEqual() 】考虑了数据类型
assert.notStrictEqual({ a: "foo" }, { a: "foo" }); assert.notStrictEqual(() => { }, () => { }); assert.notStrictEqual([], []);
上面代码是对引用类型的测试,全部通过,以上表达式是恒通过的。
6.2 assert.notDeepStrictEqual(actual, expected[, message])
notDeepStrictEqual()就是deepStrictEqual()的逆运算,如果 actual !== expected 则断言通过,否则抛出AssertionError。
assert.notDeepStrictEqual({ a: '1' }, { a: 1 }); //断言通过 assert.notDeepStrictEqual({ a: '1' }, { a: "1" }); //AssertionError [ERR_ASSERTION]: { a: '1' } notDeepStrictEqual { a: '1' }
七. 断言错误并抛出
这一组有 四 个(可以说是 三 个)测试函数,是对错误进行的处理。
7.1 assert.fail(message)
这个测试函数不多说,可以看错是下一个函数的重载,用于主动抛出带有【message】属性的【AssertionError】对象
assert.fail("自定义错误信息"); // AssertionError [ERR_ASSERTION]: 自定义错误信息
7.2 assert.fail(actual, expected[, message[, operator[, stackStartFunction]]])
该测试函数用于主动抛出自定义错误信息,抛出错误信息格式:【actual 参数 + operator 参数 + expected 参数】
assert.fail("BLUE","PINK"); // AssertionError [ERR_ASSERTION]: 'BLUE' != 'PINK'
上面代码不提供【message】和【operator】,则【operator】默认为 【!=】
assert.fail("BLUE","PINK","自定义的错误信息"); // AssertionError [ERR_ASSERTION]: 自定义的错误信息 assert.fail("BLUE","PINK","自定义的错误信息","?",()=>{ console.log("hello"); }); // AssertionError [ERR_ASSERTION]: 自定义的错误信息
上面代码提供【message】,这时候 【actual】、【operator】、【expected】等参数会被列入错误对象属性中
assert.fail("BLUE","PINK",undefined); // AssertionError [ERR_ASSERTION]: 'BLUE' undefined 'PINK' assert.fail("BLUE","PINK",undefined,"?"); // AssertionError [ERR_ASSERTION]: 'BLUE' ? 'PINK'
上面代码是【message】为 undefined 时,会检测【operator】参数,【operator?operator:undefined 】
7.3 assert.throws(block,error, message)
参数说明:
block | Function
error | RegExp | Function
message | any
【说明!!】如果block抛出的错误满足error参数,也就是抛出错误与期望一致,则断言通过,否则抛出block中的错误,如果block不抛出错误,则抛出【AssertionError 】。
【提示!!】error 参数可以是构造函数、正则表达式、或自定义函数。
assert.throws( () => { throw new Error('错误信息'); }, Error );
上面代码中 error 参数为构造函数,【block】抛出的错误与预期的一致,所以断言通过。
assert.throws( () => { throw new Error('错误信息'); }, /错误/ );
上面代码中 error 参数为正则表达式,【block】抛出的错误满足正则表达式,所以断言通过。
【注意!!】error 参数不能是字符串。 如果第二个参数是字符串,则视为省略 error 参数,传入的字符串会被用于 【message】 参数,
// 这是错误的!不要这么做! assert.throws(myFunction, '错误信息', '没有抛出期望的信息'); // 应该这么做。 assert.throws(myFunction, /错误信息/, '没有抛出期望的信息');
下面代码,【error】 参数为自定义函数
assert.throws( () => { throw new Error('错误信息'); }, function (err) { if ((err instanceof Error) && /错误/.test(err)) { return true; } }, '不是期望的错误' );
7.4 assert.doesNotThrow(block, error, message)
【说明!!】预期的错误和实际的错误一致时,不抛出实际错误,抛出AssertionError,不一致则抛出实际错误信息
assert.doesNotThrow( () => { throw new TypeError('错误信息'); }, SyntaxError );
以上例子会抛出 TypeError,因为在断言中没有匹配的错误类型
assert.doesNotThrow( () => { throw new TypeError('错误信息'); }, TypeError );
以上例子会抛出一个带有 Got unwanted exception (TypeError).. 信息的 AssertionError
assert.doesNotThrow( () => { throw new TypeError('错误信息'); }, TypeError, '抛出错误' ); // 抛出 AssertionError: Got unwanted exception (TypeError). 抛出错误
上面代码说明:如果抛出了 AssertionError 且有给 message 参数传值,则 message 参数的值会被附加到 AssertionError 的信息中
八. 判断值是否为真
这儿只有一个测试函数了
8.1 assert.ifError(value)
如果value的值为真或者可以转换成true,则抛出value,否则断言通过。
assert.ifError(true); //抛出true assert.ifError(false); //断言通过
上面代码中是直接给出的 布尔 类型的值,如果值为 true 则会将该值抛出,否则什么也不做
assert.ifError(0); //断言通过 assert.ifError("0"); //抛出 "0" assert.ifError(1); //抛出 1 assert.ifError(new Error()); //抛出 Error,对象名称
上面代码中全部是通过 Boolean(value) 转换之后再进行的测试,利用这个特性我们可以将此测试函数用于测试回调函数的 error 参数。
相关推荐:
The above is the detailed content of Sharing examples of using assert in node.js. For more information, please follow other related articles on the PHP Chinese website!