Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paradoxical issue with mocha done() and async await

I have the following test case:

it("should pass the test", async function (done) {
        await asyncFunction();
        true.should.eq(true);
        done();
    });

Running it asserts:

Error: Resolution method is overspecified. Specify a callback or return a Promise; not both.

And if I remove the done(); statement, it asserts:

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

How to solve this paradox?

like image 793
Alon Avatar asked Sep 14 '17 10:09

Alon


1 Answers

You need to remove the done parameter as well, not just the call to it. Testing frameworks like Mocha look at the function's parameter list (or at least its arity) to know whether you're using done or similar.

Using Mocha 3.5.3, this works for me (had to change true.should.be(true) to assert.ok(true) as the former threw an error):

const assert = require('assert');

function asyncFunction() {
    return new Promise(resolve => {
        setTimeout(resolve, 10);
    });
}

describe('Container', function() {
  describe('Foo', function() {
    it("should pass the test", async function () {
        await asyncFunction();
        assert.ok(true);
    });
  });
});

But if I add done:

describe('Container', function() {
  describe('Foo', function() {
    it("should pass the test", async function (done) {  // <==== Here
        await asyncFunction();
        assert.ok(true);
    });
  });
});

...then I get

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

like image 59
T.J. Crowder Avatar answered Oct 21 '22 13:10

T.J. Crowder