What is “assert” in JavaScript?

2019-01-12 14:13发布

问题:

What does assert mean in JavaScript?

I’ve seen something like:

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

And would like to know what the method assert() does.

回答1:

There is no assert in JavaScript (yet; there's talk of adding one, but it's at an early stage). Perhaps you're using some library that provides one. The usual meaning is to throw an error if the expression passed into the function is false; this is part of the general concept of assertion checking. Usually assertions (as they're called) are used only in "testing" or "debug" builds and stripped out of production code.

Suppose you had a function that was supposed to always accept a string. You'd want to know if someone called that function with something that wasn't a string. So you might do:

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

...where assert would throw an error if the condition were false.

A very simple version would look like this:

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

Better yet, make use of the Error object if the JavaScript engine supports it (really old ones might not), which has the advantage of collecting a stack trace and such:

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

Even IE8 has Error (although it doesn't have the stack property, but modern engines [including modern IE] do).



回答2:

If using a modern browser or nodejs, you can use console.assert(expression, object).

For more information:

  • Chrome API Reference
  • Firefox Web Console
  • Firebug Console API
  • IE Console API
  • Opera Dragonfly
  • Nodejs Console API


回答3:

The other answers are good: there isn't an assert function built into ECMAScript5 (e.g. JavaScript that works basically everywhere) but some browsers give it to you or have add-ons that provide that functionality. While it's probably best to use a well-established / popular / maintained library for this, for academic purposes a "poor man's assert" function might look something like this:

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


回答4:

assert() is not a native javascript function. It is a custom function someone made. You will have to look for it on your page or in your files and post it for anybody to help determine what it's doing.



回答5:

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

it is for testing JavaScript. Amazingly, at barely five or six lines, this code provides a great level of power and control over your code, when testing.

The assert function accepts two parameters:

outcome: A boolean, which references whether your test passed or failed

description: A short description of your test.

The assert function then simply creates a list item, applies a class of either “pass” or “fail,” dependent upon whether your test returned true or false, and then appends the description to the list item. Finally, that block of coded is added to the page. It’s crazy simple, but works perfectly.



回答6:

Here is a really simple implementation of an assert function. It takes a value and a description of what you are testing.

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

If the value evaluates to true it passes.

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

If it returns false it fails.

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


回答7:

If the assertion is false, the message is displayed. Specifically, if the first argument is false, the second argument (the string message) will be be logged in the developer tools console. If the first argument is true, basically nothing happens. A simple example – I’m using 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.');


回答8:

It probably came with a testing library that some of your code is using. Here's an example of one (chances are it's not the same library as your code is using, but it shows the general idea):

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



回答9:

Previous answers can be improved in terms of performances and compatibility.

Check once if the Error object exists, if not declare it :

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

Then, each assertion will check the condition, and always throw an Error object

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

Keep in mind that the console will not display the real error line number, but the line of the assert function, which is not useful for debugging.



回答10:

If you use webpack, you can just use the node.js assertion library. Although they claim that it's "not intended to be a general purpose assertion library", it seems to be more than OK for ad hoc assertions, and it seems no competitor exists in the Node space anyway (Chai is designed for unit testing).

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

You need to use webpack or browserify to be able to use this, so obviously this is only useful if those are already in your workflow.



回答11:

In addition to other options like console.assert or rolling your own, you can use invariant. It has a couple of unique features:

  • It supports formatted error messages (using a %s specifier).
  • In production environments (as determined by the Node.js or Webpack environment), the error message is optional, allowing for (slightly) smaller .js.


回答12:

Word or function "assert" is mostly used in testing parts of application.

Assert functions are a short way of instructing the program to check the condition (also called "assertion") and if the condition is not True, it will throw error.

So let's see how it would look like in "normal code"

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

With assert you can simply write:

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

In Javascript, there's no native assert function, so you have to use one from some library.

For simple introduction, you can check this article:

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

I hope it helps.