0

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?

phoenixdown
  • 828
  • 1
  • 10
  • 16
  • 2
    `sourceCode.myFunc(idontexist)` executes your function immediately and passes the return value to `assert.throws()`. `() => sourceCode.myFunc(idontexist)` is a callback that `assert.throws()` can execute when it needs to – Phil Sep 07 '21 at 23:39
  • Does `do a bunch of stuff` reference `this`? – Chris Sep 07 '21 at 23:39
  • Consider this: `() => 1` and `1` are not the same. The first one is a function, the second one is a number. Read the Mocha.js documentation to learn what `assert.throws` expects as the first argument. – Sebastian Simon Sep 07 '21 at 23:42
  • Thanks, @SebastianSimon which documentation do you recommend? I'm not finding it on https://mochajs.org/api/ or on https://mochajs.org homepage. – phoenixdown Sep 07 '21 at 23:50
  • @phoenixdown Wherever `require('assert')` comes from. – Sebastian Simon Sep 07 '21 at 23:51

0 Answers0