Assert 断言
assert 断言
// 不会跑出 AssertionError,因为 RegExp 对象的属性不是可枚举的 assert.deepEqual(/a/gi, new Date());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); // 测试通过,对象与自身相等。 assert.deepEqual(obj1, obj2); // 抛出 AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } } // 因为 b 属性的值不同。 assert.deepEqual(obj1, obj3); // 测试通过,两个对象相等。 assert.deepEqual(obj1, obj4); // 抛出 AssertionError: { a: { b: 1 } } deepEqual {} // 因为不测试原型。const assert = require('assert'); assert.deepEqual({ a: 1 }, { a: '1' }); // 测试通过,因为 1 == '1'。 assert.deepStrictEqual({ a: 1 }, { a: '1' }); // 抛出 AssertionError: { a: 1 } deepStrictEqual { a: '1' } // 因为使用全等运算符 1 !== '1'。 // 以下对象都没有自身属性。 const date = new Date(); const object = {}; const fakeDate = {}; Object.setPrototypeOf(fakeDate, Date.prototype); assert.deepEqual(object, fakeDate); // 测试通过,不测试原型。 assert.deepStrictEqual(object, fakeDate); // 抛出 AssertionError: {} deepStrictEqual Date {} // 因为原型不同。 assert.deepEqual(date, fakeDate); // 测试通过,不测试类型标签。 assert.deepStrictEqual(date, fakeDate); // 抛出 AssertionError: 2017-03-11T14:25:31.849Z deepStrictEqual Date {} // 因为类型标签不同。 assert.deepStrictEqual(new Number(1), new Number(2)); // Fails because the wrapped number is unwrapped and compared as well. assert.deepStrictEqual(new String('foo'), Object('foo')); // OK because the object and the string are identical when unwrapped.
注意事项
Last updated