Thursday 1 June 2017

Mocha unit tests not calling function generators within an object

I have an object containing a number of function* type generators that I'm trying to write Mocha unit tests for. However, Mocha will not call the functions and I'm having a hard time figuring out what the solution is.

Here is some example code:

'use strict';

var ctr = {
        fn: function(arg,cb) {
                console.log( 'arg:', arg );
                var err = (arg == true);
                return cb( err, arg );
        }
};

describe( 'Mocha test', function() {
        it( 'should call the function', function(done) {
                console.log('a');
                ctr.fn( false, function(err,data) {
                        console.log('b');
                        if( err ) return done(err);
                        console.log('c');
                        done();
                        console.log('d');
                });
                console.log('e');
        });
});

When I run $ mocha testfile.js I get this output:

  Mocha test
a
arg: false
b
c
    ✓ should call the function (39ms)
d
e
  1 passing (172ms)

That's all as expected. However, If I replace "fn: function(..." with "fn: function*(...", running $ mocha testfile.js results in:

  Mocha test
a
e
    1) should call the function


  0 passing (2s)
  1 failing

  1) Mocha test should call the function:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

I thought I found the answer with this Mocha plugin, but running mocha -r mocha-plugin-co testfile.js gives the same result as not specifying it.

I think I need to "make sure the Promise resolves", but it's not clear to me what that means. I'm not [intentionally] using Promises, but the npm package I'm using wants the functions defined in this form.

Is there a simple solution to make mocha work the way I expect here, or do I need to go change all my code to regular functions and hope nothing breaks?



via rand'Chris

No comments:

Post a Comment