I have a function in some nodejs code like this:
function myFunc(input){
let somevar = otherFunc(input);
//do a bunch of stuff
}
When I write my tests in Mocha I have noticed something I don't understand.
Version 1:
//this won't work
var sourceCode = require('../mysourcecodefile.js');
const assert = require('assert');
describe('myFunc function', function(){
it('throws an exception if the input does not exist', function(){
let input = idontexist;
assert.throws(
sourceCode.myFunc(idontexist),
/.*my specific error message text.*/ //won't be found
);
})
})
Version 2:
//this will work
var sourceCode = require('../mysourcecodefile.js');
const assert = require('assert');
describe('myFunc function', function(){
it('throws an exception if the input does not exist', function(){
let input = idontexist;
assert.throws(
() => sourceCode.myFunc(idontexist),
/.*my specific error message text.*/ //will be found
);
})
})
In Version 1 there is an error from otherFunc()
that gets thrown first, so the regex /.*my specific error message text.*/
does not match.
In Version 2 for some reason it seems like otherFunc()
is skipped, and myFunc()
correctly throws its own error that matches /.*my specific error message text.*/
.
What is happening in Version 2, and why does it work when Version 1 fails?
My best guess is that Version 2 is using arrow functions to pass an anonymous lambda function through the Mocha framework, which somehow tells it to auto mock any subfunctions and I guess just skip them? Is this something Mocha or javascript does under the hood?