Node assert.throws not catching exception

前端 未结 4 729
死守一世寂寞
死守一世寂寞 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: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 );
    

提交回复
热议问题