What is “assert” in JavaScript?

2019-01-12 13:56发布

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.

12条回答
霸刀☆藐视天下
2楼-- · 2019-01-12 14:25

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.

查看更多
乱世女痞
3楼-- · 2019-01-12 14:26

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.

查看更多
相关推荐>>
4楼-- · 2019-01-12 14:28

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

查看更多
甜甜的少女心
5楼-- · 2019-01-12 14:34

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.

查看更多
小情绪 Triste *
6楼-- · 2019-01-12 14:35

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

For more information:

查看更多
贼婆χ
7楼-- · 2019-01-12 14:35

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.');
查看更多
登录 后发表回答