Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

unit testing - Node assert.throws not catching exception

Given this code:

var assert = require('assert');

function boom(){
    throw new Error('BOOM');
}

assert.throws( boom(), Error );

I get this output, with node 0.4.9:

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: BOOM
    at boom ([EDITED]/assert.throws.test.js:4:9)
    at Object.<anonymous> ([EDITED]/assert.throws.test.js:7:17)
    at Module._compile (module.js:402:26)
    at Object..js (module.js:408:10)
    at Module.load (module.js:334:31)
    at Function._load (module.js:293:12)
    at Array.<anonymous> (module.js:421:10)
    at EventEmitter._tickCallback (node.js:126:26)

This, to me, implies that an uncaught exception has occurred, as opposed to a reported, caught exception. Looking in the docs, I notice that the examples look more like this:

var assert = require('assert');

function boom(){
    throw new Error('BOOM');
}

assert.throws( boom, Error );

But how do you test if it throws an exception given a certain input? For example:

var assert = require('assert');

function boom(blowup){
    if(blowup)
        throw new Error('BOOM');
}

assert.throws( boom, Error );

This will fail. What am I doing wrong, or what secret does everybody know but me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The examples take a function, while your sample code calls a function and passes the result. The exception happens before the assert even gets to look at it.

Change your code to this:

var assert = require('assert');

function boom(){
    throw new Error('BOOM');
}

assert.throws( boom, Error ); // note no parentheses

EDIT: To pass parameters, just make another function. After all, this is javascript!

var assert = require('assert');

function boom(blowup){
    if(blowup)
        throw new Error('BOOM');
}

assert.throws( function() { boom(true); }, Error );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...