什么是JavaScript中的“断言”?

时间:2013-03-09 17:00:17

标签: javascript assert

assert在JavaScript中意味着什么?

我见过这样的话:

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

想知道方法assert()的作用。

16 个答案:

答案 0 :(得分:346)

JavaScript中没有assert(还有talk of adding one,但它处于早期阶段)。也许你正在使用一些提供一个库的库。通常的意思是如果传递给函数的表达式为false则抛出错误;这是assertion checking的一般概念的一部分。通常断言(因为它们被称为)仅用于“测试”或“调试”构建并从生产代码中删除。

假设您有一个应该总是接受字符串的函数。你想知道是否有人用不是字符串的东西调用了那个函数。所以你可以这样做:

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

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

一个非常简单的版本看起来像这样:

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

更好的是,如果JavaScript引擎支持它,可以使用Error对象(实际上可能不支持),这样可以收集堆栈跟踪等等:

function assert(condition, message) {
    if (!condition) {
        message = message || "Assertion failed";
        if (typeof Error !== "undefined") {
            throw new Error(message);
        }
        throw message; // Fallback
    }
}

即使IE8有Error(虽然它没有stack属性,但是现代引擎[包括现代IE]都有。)

答案 1 :(得分:149)

如果使用现代浏览器或nodejs,您可以使用console.assert(expression, object)

了解更多信息:

答案 2 :(得分:27)

其他答案都很好:ECMAScript5中没有内置的断言功能(例如,JavaScript基本上可以在任何地方使用),但有些浏览器会将其提供给您或者具有提供该功能的附加组件。尽管最好使用一个成熟/受欢迎/维护的库,但出于学术目的,“穷人的断言”功能可能看起来像这样:

const assert = function(condition, message) {
    if (!condition)
        throw Error('Assert failed: ' + (message || ''));
};

assert(1 === 1); // Executes without problem
assert(false, 'Expected true');
// Yields 'Error: Assert failed: Expected true' in console

答案 3 :(得分:8)

assert()不是原生的javascript函数。这是一个人做的自定义功能。您必须在您的页面或文件中查找它并将其发布给任何人以帮助确定它正在做什么。

答案 4 :(得分:5)

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

用于测试JavaScript。令人惊讶的是,在测试时,这段代码只需要五到六行,就可以为代码提供强大的功能和控制。

assert函数接受两个参数:

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

description:测试的简短描述。

断言函数然后简单地创建一个列表项,应用“pass”或“fail”的类,这取决于您的测试是返回true还是false,然后将描述附加到列表项。最后,将该编码块添加到页面中。这很简单,但效果很好。

答案 5 :(得分:4)

这是一个非常简单的断言函数实现。它需要一个值和您正在测试的内容的描述。

 function assert(value, description) {
        var result = value ? "pass" : "fail";
        console.log(result + ' - ' +  description); 
    };

如果值的计算结果为true,则传递。

assert (1===1, 'testing if 1=1');  

如果返回false则失败。

assert (1===2, 'testing if 1=1');

答案 6 :(得分:4)

如果断言为false,则显示消息。具体来说,如果第一个参数为false,则第二个参数(字符串消息)将记录在开发人员工具控制台中。如果第一个参数为真,基本上没有任何反应。一个简单的例子 - 我正在使用Google Developer Tools:

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.');

答案 7 :(得分:3)

它可能带有一些代码正在使用的测试库。这是一个例子(很可能它不是你的代码使用的库,但它显示了一般的想法):

http://chaijs.com/guide/styles/#assert

答案 8 :(得分:3)

如果第一个属性为false,则第二个属性为要抛出的消息,则断言将引发错误消息。

console.assert(condition,message);

有很多评论说断言在JavaScript中不存在,但是console.assert()是JavaScript中的断言函数 断言的目的是找出错误发生的原因/位置。

console.assert(document.getElementById("title"), "You have no element with ID 'title'");
console.assert(document.getElementById("image"), "You have no element with ID 'image'");

在此根据消息可以找到错误所在。 这些错误消息将以红色显示在控制台上,就像我们调用console.error();

您可以使用断言来测试您的功能,例如:

console.assert(myAddFunction(5,8)===(5+8),"Failed on 5 and 8");

请注意条件可以是!= < >

通常用于通过提供一些测试用例来测试新创建的函数是否按预期工作,而不是用于生产。

要查看控制台中的更多功能,请执行console.log(console);

答案 9 :(得分:2)

单词或函数“ assert”通常用于测试应用程序的一部分。

Assert函数是指示程序检查条件(也称为“断言”)的一种简短方法,如果条件不为True,则会引发错误。

因此,让我们看一下它在“普通代码”中的样子

if (typeof "string" === "array") { throw Error('Error: "string" !== "array"'); }

使用assert,您可以简单地编写:

assert(typeof "string" === "array")

在Javascript中,没有本地assert函数,因此您必须使用某个库中的一个。

为简单介绍,您可以查看这篇文章:

http://fredkschott.com/post/2014/05/nodejs-testing-essentials/

希望对您有帮助。

答案 10 :(得分:1)

以前的答案可以在性能和兼容性方面得到改善。

检查一次,如果Error对象存在,如果没有声明它:

if (typeof Error === "undefined") {
    Error = function(message) {
        this.message = message;
    };
    Error.prototype.message = "";
}

然后,每个断言都会检查条件,总是抛出一个Error对象

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

请记住,控制台不会显示真实的错误行号,而是显示assert函数的行,这对调试没有用。

答案 11 :(得分:1)

如果您使用webpack,则可以使用node.js assertion library。虽然他们声称它“并不打算成为一个通用断言库”,但对于临时断言来说似乎还不错,而且似乎在节点空间中没有竞争对手(Chai专为单元测试而设计)。 / p>

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

您需要使用webpack或browserify才能使用它,所以显然只有在您的工作流程中已经存在这些内容时才有用。

答案 12 :(得分:1)

console.assertrolling your own等其他选项外,您还可以使用invariant。它有几个独特的功能:

  • 它支持格式化的错误消息(使用%s说明符)。
  • 在生产环境中(由Node.js或Webpack环境确定),错误消息是可选的,允许(稍微)更小的.js。

答案 13 :(得分:0)

如T.J.所述,JavaScript中没有assert。 但是,有一个名为assert的节点模块,即used mostly for testing。因此,您可能会看到类似以下的代码:

const assert = require('assert');
assert(5 > 7);

答案 14 :(得分:0)

Java 有一个 assert 语句,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');

答案 15 :(得分:0)

Node.js 实际上有一个可以导入的 assert 函数。

const assert = require('assert')

它的工作原理与人们预期的完全一样,即 assert(false) 抛出一个错误,而 assert(false, message) 抛出一个带有消息的错误。

其他答案已经指出 JS 本身没有原生的断言功能,并且在撰写本文时(2021 年 4 月)仍然如此。