Mocha,如何在没有UnhandledPromiseRejectionWarning的情况下测试异步代码

Mocha, how to test async code without UnhandledPromiseRejectionWarning

我正在使用 mochajs 测试我的服务器端 api 端点,但我不知道如何正确地进行测试。

我从具有以下逻辑的代码开始:

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();
    });
});

但是测试并没有失败,因为它抛出了请求处理回调。

所以我四处搜索,发现我的问题可以使用 promises 解决,确实如此,现在测试失败了。这是生成的代码:

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);
    });
});

但现在我收到了弃用警告,因为错误是在与抛出错误的进程不同的进程中处理的。

错误是:UnhandledPromiseRejectionWarningPromiseRejectionHandledWarning

发送响应后如何使我的测试失败,并避免出现 unhandledPromiseRejectionWarning?

这个有效

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

    let bindRequestHandler = new Promise((reslove, reject) => {

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

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

            try { // Here, we need a try/catch/reject logic because we're in a callback (not in the promise scope)

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

            } catch (error) { // Catch the failing test errors and reject them
                reject(error);
            }

            resolve();
        });
    });

    let sendRequest = new Promise((reslove, reject) => {
        // Launch request
        requests.get(url('/test'), (err, resp, body) => { // Handle response

            try {

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

            } catch (error) { // Catch the failing test errors and reject them
                reject(error);
            }

            reslove();
        });
    });

    Promise.all([bindRequestHandler, sendRequest])
        .then(res => doneFn())
        .catch(doneFn);
});