Laoujin
Laoujin

Reputation: 10229

NodeJS function parameter checking with assertions

NodeJS' dynamic typing is fun and all but given a function I'd like to get some feedback during development whether what I'm passing is in fact going to produce anything meaningful.

In C# I would do: Debug.Assert(complexType.Title.length <= 10) (such statements would not be included when compiled in release mode)

I found that for example Chai could do exactly this. However this is a BDD / TDD framework and I plan on putting this in production code, not in tests.

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

I read that this could be compiled out with Uglify to more closely reflect Debug.Assert behaviour.

Is this a good idea? Or does NodeJS have 'real' assertions?

Upvotes: 4

Views: 2852

Answers (1)

Ozk
Ozk

Reputation: 191

You can use the built-in assert template for assertion testing. You can also use the built-in arguments object to test the arguments you receive to the function. Here's an example:

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

Plus, there's more stuff you can do with the built-in arguments object but I guess the OP is more about the assert functionality.

Upvotes: 3

Related Questions