Node assert.throws not catching exception

前端 未结 4 730
死守一世寂寞
死守一世寂寞 2020-12-15 03:49

Given this code:

var assert = require(\'assert\');

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

assert.throws( boom(), Error );

I ge

相关标签:
4条回答
  • 2020-12-15 04:13

    Current node stable (v4.1) includes fat arrow function support by default (no --harmony flag required) so you can do something like:

    assert.throws(()=>boom(), Error);
    assert.throws(()=>boom(true), Error); // with params
    

    Even if you have parentheses after boom() (so you're actually invoking it, instead of passing a reference to the function object), by using the fat arrow function you're wrapping it in a block, which is what assert.throws expects.

    0 讨论(0)
  • 2020-12-15 04:18

    You can use bind():

    assert.throws( boom.bind(null), Error );
    

    With arguments it is:

    assert.throws( boom.bind(null, "This is a blowup"), Error );
    
    0 讨论(0)
  • 2020-12-15 04:21

    This is closely related to the issue people with with other assertion Mocha/Chai. See this answer for the description with node examples:
    Mocha / Chai expect.to.throw not catching thrown errors

    0 讨论(0)
  • 2020-12-15 04:23

    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 );
    
    0 讨论(0)
提交回复
热议问题