使用断言检查 NodeJS 函数参数

NodeJS function parameter checking with assertions

NodeJS 的动态类型很有趣,除了给定一个函数外,我想在开发过程中得到一些反馈,看看我传递的内容是否真的会产生任何有意义的东西。

在 C# 中我会这样做:Debug.Assert(complexType.Title.length <= 10)(在发布模式下编译时不会包含此类语句)

我发现例如 Chai 就可以做到这一点。然而,这是一个 BDD / TDD 框架,我计划将其放入生产代码中,而不是测试中。

function doSomething(complexType) {
    expect(complexType.title).to.be.a('string');
}

我读到这可以用 Uglify 编译出来以更准确地反映 Debug.Assert 行为。

这是个好主意吗?或者 NodeJS 有 'real' 断言吗?

您可以使用内置的 assert 模板进行断言测试。 您还可以使用内置的 arguments 对象来测试您收到的函数参数。这是一个例子:

var assert = require('assert');

var doSomething () {
 if (arguments.length > 0) { // And you might even not need the if clause here...
  assert.equal(typeof arguments[0], 'string');
 }
}

doSomething('This is my title');
doSomething(1); // This will trigger the assert

此外,您可以使用内置的 arguments 对象做更多的事情,但我猜 OP 更多的是关于断言功能。