断言在JavaScript中是什么意思?

我见过这样的情况:

assert(function1() && function2() && function3(), "some text");

并且想知道assert()方法做什么。


当前回答

如果断言为假,则显示该消息。具体来说,如果第一个参数为假,则第二个参数(字符串消息)将被记录在开发人员工具控制台中。如果第一个参数是正确的,基本上什么都不会发生。一个简单的例子-我使用谷歌开发工具:

var isTrue = true;
var isFalse = false;
console.assert(isTrue, 'Equals true so will NOT log to the console.');
console.assert(isFalse, 'Equals false so WILL log to the console.');

其他回答

JavaScript本身没有标准的断言。也许你使用的库提供了这样的功能;例如,如果你在使用Node.js,也许你在使用断言模块。(提供实现控制台API的控制台的浏览器和其他环境提供console.assert。)

assert函数的通常含义是,如果传入函数的表达式为false,则抛出一个错误;这是断言检查一般概念的一部分。通常断言(正如它们所称)只在“测试”或“调试”构建中使用,并从生产代码中剥离出来。

假设有一个函数总是接受字符串。你会想知道是否有人用不是字符串的东西(没有像TypeScript或Flow这样的类型检查层)调用了这个函数。你可能会这样做:

assert(typeof argumentName === "string");

...如果条件为假,assert将抛出错误。

一个非常简单的版本是这样的:

function assert(condition, message) {
    if (!condition) {
        throw message || "Assertion failed";
    }
}

更好的是,利用Error对象,它具有收集堆栈跟踪的优点,例如:

function assert(condition, message) {
    if (!condition) {
        throw new Error(message || "Assertion failed");
    }
}

如果你使用webpack,你可以只使用node.js断言库。尽管他们声称它“并不是一个通用的断言库”,但它对于特别的断言似乎已经足够了,而且在Node领域似乎没有竞争对手(Chai是为单元测试而设计的)。

const assert = require('assert');
...
assert(jqXHR.status == 201, "create response should be 201");

你需要使用webpack或browserify才能使用它,所以很明显,这只在那些已经在你的工作流中才有用。

Java有一个断言语句,JVM默认禁用断言验证。它们必须使用命令行参数-enableassertions(或其简写-ea)显式启用,

虽然JavaScript支持console.assert(),但它只是一个日志方法,如果断言失败也不会中断当前过程。

为了把东西放在一起并满足各种需求,这里有一个小的js断言库。

globalThis.assert = (()=> { class AssertionError extends Error { constructor(message) { super(message); this.name = 'AssertionError'; } } let config = { async: true, silent: false }; function assert(condition, message = undefined) { if (!condition) { if (config.silent) { //NOOP } else if (config.async) { console.assert(condition, message || 'assert'); } else { throw new AssertionError(message || 'assertion failed'); } } } assert.config = config; return assert; })(); /* global assert */ Object.assign(assert.config, { // silent: true, // to disable assertion validation async: false, // to validate assertion synchronously (will interrupt if assertion failed, like Java's) }); let items = [ {id: 1}, {id: 2}, {id: 3} ]; function deleteItem(item) { let index = items.findIndex((e)=> e.id === item.id); assert(index > -1, `index should be >=0, the item(id=${item.id}) to be deleted doesn't exist, or was already deleted`); items.splice(index, 1); } console.log('begin'); deleteItem({id: 1}); deleteItem({id: 1}); console.log('end');

Chrome开发工具支持console.assert 你可以打开devtools并在devtools-source-navigator- snippets中创建一个代码段。然后写一些代码……并运行代码片段…

检查:http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-quick-and-easy-javascript-testing-with-assert/

它是用来测试JavaScript的。令人惊讶的是,这段代码只有五六行,在测试时提供了强大的功能和对代码的控制。

assert函数接受两个形参:

outcome:一个布尔值,它引用您的测试是通过还是失败

描述:测试的简短描述。

assert函数然后简单地创建一个列表项,应用一个“pass”或“fail”的类(取决于您的测试返回的是真还是假),然后将描述追加到列表项。最后,该编码块被添加到页面中。这是疯狂的简单,但工作完美。