1. 关于Node Assert
顾名思义应该就是跑测试用例里的断言吧,里面有各种接口判断
assert() 和true比较
assert.deepEqual(v1,v2,[message])把v1,v2进行比较,针对对象的比较
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);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
// values of b are different
assert.deepEqual(obj1, obj3);
// OK, objects are equal
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
// Prototypes are ignored
assert.deepStrcitEqual(v1,v2,[message])比较v1,v2, 针对对象,会深层遍历对象,执行===规则比较
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
assert.doesNotThrow(block,[message])直接执行block内容,如果block块抛出的异常类型和指定的异常类型相同,则抛出AssertionError, 反之则抛出指定的异常
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
SyntaxError
);
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError
);
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError,
'Whoops'
);
// Throws: AssertionError: Got unwanted exception (TypeError). Whoops
assert.equal(v1,v2,message)
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}});
//AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
assert.fail(actual, expected, message, operator)总是抛出AssertError异常无论是否满足条件,将actual和expected用operator比较,如果message为false则AssertError信息为actual operator expected, 如果message为true则显示message
assert.fail(1, 2, undefined, '>');
// AssertionError: 1 > 2
assert.fail(1, 2, 'whoops', '>');
// AssertionError: whoops
Note:运行assert.fail(1, 2, undefined, '<'); 输出:AssertionError: 1<2
assert.ifError(value) 当value为true时输出value
const assert = require('assert');
assert.ifError(0); // OK
assert.ifError(1); // Throws 1
assert.ifError('error') // Throws 'error'
assert.ifError(new Error()); // Throws Error
assert.notDeepEqual(actual, expected[, message]) 和assert.deepEqual(actual, expected[, message]) 相反
assert.notDeepStrictEqual(actual, expected[, message])和assert.deepStrictEqual(actual, expected[, message])相反
assert.ok(value[, message])测试value是否为true, 否则抛出AssertError异常
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');
// throws "AssertionError: it's false"
assert.strictEqual(actual, expected[, message])比较规则和===相同
assert.strictEqual(1, 2);
// AssertionError: 1 === 2
assert.strictEqual(1, 1);
// OK
assert.strictEqual(1, '1');
// AssertionError: 1 === '1'
assert.throws(block[, error][, message])期望block抛出异常,error不可以是string类型