assert模塊是Node的內置模塊,主要用於斷言。若是表達式不符合預期,就拋出一個錯誤,可用於測試模塊功能,有少數幾個是經常使用的。javascript
通用概念:html
* actual:實際的值 * expeacted:預期的值 * message:報錯時候拋出的錯誤參數
const assert = require('assert'); assert(true); // OK assert(1); // OK assert(false); // throws "AssertionError: false == true" assert(0); // throws "AssertionError: 0 == true" assert(false, 'it\'s false'); // throws "AssertionError: it's false"
比較實際值是否等於預期值。至關於===java
const assert = require('assert'); const obj1 = { a : { b : 1 } }; const obj2 = { a : { b : 2 } }; const obj3 = { a : { b : 1 } }; const obj4 = Object.create(obj1); assert.deepEqual(obj1, obj1); // OK, object is equal to itself assert.deepEqual(obj1, obj2);
注意點 deepStrictEqual至關於===node
const assert = require('assert'); assert.deepEqual({a:1}, {a:'1'}); // OK, because 1 == '1' assert.deepStrictEqual({a:1}, {a:'1'}); // AssertionError: { a: 1 } deepStrictEqual { a: '1' } // because 1 !== '1' using strict equality
doesNotThrow預期不同的時候,預期某個代碼塊不拋出錯誤api
assert.doesNotThrow( () => { throw new TypeError('Wrong value'); }, SyntaxError );
注意點:equal方法內部使用的是相等運算符(==),而不是嚴格運算符(===),進行比較運算。oop
const assert = require('assert'); assert.equal(1, 1); // OK, 1 == 1 assert.equal(1, '1'); // OK, 1 == '1' assert.equal(1, 2); // AssertionError: 1 == 2 assert.equal({a: {b: 1}}, {a: {b: 1}});
fail方法用於拋出一個錯誤測試
const assert = require('assert'); assert.fail(1, 2, undefined, '>'); // AssertionError: 1 > 2 assert.fail(1, 2, 'whoops', '>');
ifError方法斷言某個表達式是否falseui
const assert = require('assert'); assert.ifError(0); // OK assert.ifError(1); // Throws 1 assert.ifError('error'); // Throws 'error' assert.ifError(new Error()); // Throws Error
const assert = require('assert'); const obj1 = { a : { b : 1 } }; const obj2 = { a : { b : 2 } }; const obj3 = { a : { b : 1 } }; const obj4 = Object.create(obj1); assert.notDeepEqual(obj1, obj1); // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } assert.notDeepEqual(obj1, obj2); // OK, obj1 and obj2 are not deeply equal
const assert = require('assert'); assert.notEqual(1, 2); // OK assert.notEqual(1, 1); // AssertionError: 1 != 1 assert.notEqual(1, '1'); // AssertionError: 1 != '1'
比較值,至關於==spa
const assert = require('assert'); assert.notDeepEqual({a:1}, {a:'1'}); // AssertionError: { a: 1 } notDeepEqual { a: '1' } assert.notDeepStrictEqual({a:1}, {a:'1'}); // OK
ok是assert方法的另外一個名字,與assert方法徹底同樣。code
const assert = require('assert'); assert.ok(true); // OK assert.ok(1); // OK assert.ok(false); // throws "AssertionError: false == true" assert.ok(0); // throws "AssertionError: 0 == true" assert.ok(false, 'it\'s false');
至關於比較 ===
const assert = require('assert'); assert.strictEqual(1, 2); // AssertionError: 1 === 2 assert.strictEqual(1, 1); // OK assert.strictEqual(1, '1'); // AssertionError: 1 === '1'
throws方法預期某個代碼塊會拋出一個錯誤,且拋出的錯誤符合指定的條件
assert.throws( () => { throw new Error('Wrong value'); }, Error );
*nodejs的環境: