Javascript 如何断言不为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29464849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:24:03  来源:igfitidea点击:

How to assert not null?

javascriptnode.jsmocha

提问by Hosar

I'm very new in javascript testing, I would like to know how to assert not null in Mochaframework.

我在 javascript 测试方面很新,我想知道如何在Mocha框架中断言不为空。

回答by André Pena

Mocha supports any assertion library you want. You can take a look at how it deals with assertions here: http://mochajs.org/#assertions. I don't know which one you want to use.

Mocha 支持您想要的任何断言库。您可以在此处查看它如何处理断言:http: //mochajs.org/#assertions。不知道你想用哪一种。

Considering you are using Chai, which is pretty popular, here are some options:

考虑到您正在使用非常受欢迎的Chai,这里有一些选择:

Consider "foo" to be the target variable you want to test

将“foo”视为您要测试的目标变量

Assert

断言

var assert = chai.assert;
assert(foo) // will pass for any truthy value (!= null,!= undefined,!= '',!= 0)
// or
assert(foo != null)
// or
assert.notEqual(foo, null);

In case you want to use assert, you don't even need Chai. Just use it. Node supports it natively: https://nodejs.org/api/assert.html#assert_assert

如果您想使用assert,您甚至不需要 Chai。就用它。Node 本身支持它:https: //nodejs.org/api/assert.html#assert_assert

Should

应该

var should = require('chai').should();
should.exist(foo); // will pass for not null and not undefined
// or
should.not.equal(foo, null);

Expect

预计

var expect = chai.expect;
expect(foo).to.not.equal(null);
// or
expect(foo).to.not.be.null;

PS: Unrelated but on Jest there is a toBeNullfunction. You can do expect(foo).not.toBeNull();or expect(foo).not.toBe(null);

PS:无关但在 Jest 上有一个toBeNull功能。你可以做expect(foo).not.toBeNull();expect(foo).not.toBe(null);

回答by kat

This is what worked for me (using Expectlibrary with Mocha):

这对我有用(在Mocha 中使用Expect库):

expect(myObject).toExist('Too bad when it does not.');

回答by FieryCat

In case, you're using Chai in addition to Mocha:

如果除了 Mocha 之外,您还使用 Chai:

assert.isNotNull(tea, 'great, time for tea!');