2019-07-28 Node Assert

assert.AssertionError

Error的子类

new assert.AssertionError(options)

  • message
  • actual 实际输入
  • expected 期待输入
  • operator 比较的操作(或触发错误的断言函数)
  • stackStartFn 移除所有堆栈跟踪 只保留当前 不知道里面能写点啥

严格模式

const assert = require('assert').strict;

assert.ok(value[, message])

参见 assert()

assert(value[, message])

assert.ok别名

等同 assert.equal(!!value, true, message)

  • value 判断value是否为真
  • message 为假抛出的信息

assert.deepStrictEqual(actual, expected[, message])

  • 原始值使用 SameValue比较 (Object.is)

关于相等的判断

  • 对象的类型标签(type tag)应该相同
var a;
Object.prototype.toString.call(a); // [object Undefined]
Object.prototype.toString.call([]); // [object Array]

type tag 完整列表--tc39.es

  • 使用严格相等(Strict equal ===)比较来比较对象的原型
  • 只考虑可枚举自身属性
  • 始终比较 Error 的名称和消息,即使这些不是可枚举的属性
let err1 = new Error({
  name: 'err',
  message: 'message'
});
let err2 = new Error({
  name: 'err',
  message: 'message'
});
// AssertionError [ERR_ASSERTION]: Input objects identical but not reference equal
assert.strictEqual(err1, err2); 
  • 可枚举的自身 Symbol 属性也会比较
  • 对象封装器作为对象和解封装后的值都进行比较

对象封装器: 待补充

  • Object 属性的比较是无序的。
  • Map 键名与 Set 子项的比较是无序的
  • 当两边的值不相同或遇到循环引用时,递归停止。
  • WeakMap 和 WeakSet 的比较不依赖于它们的值

Map Set WeakMap WeakSet : 待补充

assert.doesNotReject(asyncFn[, error][, message])

assert.doesNotThrow(fn[, error][, message])

  • 两个类似 断言不会出现错误
  • doesNotReject 支持异步

assert.fail([message])

抛出个错误

  • message <string> | <Error>

assert.ifError(value)

  • 如果 value 不为 undefined 或 null,则抛出 value。
  • 只有 undefined 和 null能通过

assert.notDeepStrictEqual(actual, expected[, message])

参见assert.deepStrictEqual

assert.notDeepStrictEqual({ a: 1 }, { a: '1' });// 通过

assert.strictEqual(actual, expected[, message])

  • 测试 actual 参数和 expected 参数之间的严格相等性,使用 SameValue比较。

SameValue 关于相等的判断

assert.notStrictEqual(actual, expected[, message])

参见 assert.strictEqual

测试 actual 参数和 expected 参数之间的严格不相等,使用 SameValue比较

assert.rejects(asyncFn[, error][, message])

  • 期望 asyncFn 函数抛出错误 或rejected Promise
  • 如果指定第二个参数 那么 要求抛出的错误 和 第二个参数相同 或者满足第二个的条件
  • message 自定义抛出错误的信息 不符合后 抛出的错误

assert.throws(fn[, error][, message])

和rejects差不多

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • assert模块提供了断言测试的函数,用于测试不变式 有strict和legacy两种模式,建议只使用strict...
    喵妈阅读 11,250评论 0 0
  • 步骤 全局安装 mocha Fork 代码仓库并拉到本地 启动测试 打开 ./test/test.js 修改代码跑...
    Junting阅读 10,574评论 0 1
  • assert用来做什么? assert作为Node的内置模块主要用于断言。assert模块提供了一些简单的测试功能...
    Jerry379阅读 3,332评论 0 0
  • 1. 关于Node Assert 顾名思义应该就是跑测试用例里的断言吧,里面有各种接口判断 assert() 和t...
    CindyLu91阅读 3,359评论 0 0
  • Assert Stability: 2 - Stable 稳定 Assert - Node.js 的断言库 在 N...
    小菜荔枝阅读 3,878评论 0 3

友情链接更多精彩内容