断言主要应用于“调试”与“测试”
一、前端中的断言
仔细地查找一下JavaScript中的API,实际上并没有多少关于断言的方法。唯一一个就是console.assert:
// console.assert(condition, message)
const a = '1'
console.assert(typeof a === 'number', 'a should be Number')
复制代码
当condition为false时,该方法则会将错误消息写入控制台。如果为true,则无任何反应。
实际上,很少使用console.assert方法,如果你阅读过vue或者vuex等开源项目,会发现他们都定制了断言方法:
// Vuex源码中的工具函数
function assert (condition, msg) {
if (!condition) {
throw new Error(`[Vuex] ${msg}`)
}
}
复制代码
二、Node中的断言
Node中内置断言库(assert),这里我们可以看一个简单的例子:
try {
assert(false, '这个值应该是true')
} catch(e) {
console.log(e instanceof assert.AssertionError) // true
const { actual, expected, operator } = e
console.log(`实际值: ${actual},期望值: ${expected}, 使用的运算符:${operator}`)
// 实际值: false,期望值: true, 使用的运算符:==
}
复制代码
assert模块提供了不少的方法,例如strictEqual、deepStrictEqual、notDeepStrictEqual等,仔细观察这几个方法,我们