lundi 29 janvier 2018

Mocha, how to test async code without UnhandledPromiseRejectionWarning

I'm testing my server-side api endpoints with mochajs and I can't figure out how to do it properly.

I started with code that had the following logic:

it('test', (doneFn) => {

    // Add request handler
    express.get('/test', (req, res, next) => {

        // Send response
        res.status(200).end();

        // Run some more tests (which will fail and throw an Error)
        true.should.be.false;

        // And that's the problem, normally my framework would catch the
        // error and return it in the response, but that logic can't work
        // for code executed after the response is sent.
    });

    // Launch request
    requests.get(url('/test'), (err, resp, body) => { // Handle response

        // I need to run some more tests here
        true.should.be.true;

        // Tell mocha test is finished
        doneFn();
    });
});

But the test doesn't fail (I'm guessing because doneFn() is being called in a different tick?).

So I googled around and found that my problem could be solved using promises, and it does, now the test fails. This is the resulting code:

it('test', (doneFn) => {

    let handlerPromise;

    // Add request handler
    express.get('/test', (req, res, next) => {

        // Store it in a promise
        handlerPromise = new Promise(fulfill => {

            res.status(200).end();

            true.should.be.false; // Fail

            fulfill();
        });
    });

    // Send request
    requests.get(url('/test'), (err, resp, body) => {

        // Run the other tests
        true.should.be.true;

        handlerPromise
            .then(() => doneFn()) // If no error, pass
            .catch(doneFn); // Else, call doneFn(error);
    });
});

But now I end up with a deprecation warning because the error is handled in a different process tick than the one it was thrown.

The errors are: UnhandledPromiseRejectionWarning and PromiseRejectionHandledWarning

What am I doing wrong here?

Aucun commentaire:

Enregistrer un commentaire