测试函数抛出 UnhandledPromiseRejectionWarning。导致测试不通过

Testing function throws UnhandledPromiseRejectionWarning. Causing test not to pass

我玩过摩卡测试。 我注意到我的函数在少数地方抛出了 "UnhandledPromiseRejectionWarning" 的警告。它使脚本无法通过检查。

我在 Internet 上找不到有用的示例 teach/show 解决问题的好方法。也许你们中的一个可以提供帮助。

如果您对我的代码有任何其他意见,请随时分享。我是来学习的:)

出现问题的函数。

it('/POST /logout => Logout a user by purging a session', (done) => {
        let loginInfo = {};
        loginInfo.usr = 'testuser';
        loginInfo.psw = 'mochatesting197';
        let agent = chai.request.agent(app);
        let json = {};
        json.logout = true;
        agent.post('/login')
            .send(loginInfo)
            .then((res) => {
                return agent.post('/logout')
                    .send(json)
                    .then((res) => {
                        res.should.have.status(200);
                        res.body.should.be.a('object');
                        res.body['success'].should.have.property('message').eql('YOU HAVE LOGGED OUT');
                        done();
                    }).catch(function (err) {
                        throw err;
                    });
            });
    });

当 Promise 被拒绝但没有与之关联的 catch 处理程序时,会发生 UnhandledPromiseRejectionWarning。由于处理程序可以随时附加到 Promise(即使在它被拒绝之后),默认行为是在多次事件循环后将警告记录到默认输出(控制台)。

在您提供的代码中,最可能的原因是您的 catch 块位于错误的位置。尝试将 catch 处理程序移动到 Promise 链的底部。

这不一定能解决问题,但它是您提供的代码中最有可能的地方。另外,请注意,当使用 Mocha 的 'done' 回调机制时,您不应该抛出。相反,您应该调用 done 并出现错误(如下所示)

it('/POST /logout => Logout a user by purging a session', (done) => {
    let loginInfo = {};
    loginInfo.usr = 'testuser';
    loginInfo.psw = 'mochatesting197';
    let agent = chai.request.agent(app);
    let json = {};
    json.logout = true;
    agent.post('/login')
        .send(loginInfo)
        .then((res) => {
            return agent.post('/logout')
                .send(json)
                .then((res) => {
                    res.should.have.status(200);
                    res.body.should.be.a('object');
                    res.body['success'].should.have.property('message').eql('YOU HAVE LOGGED OUT');
                    done();
                })
        })
        .catch(function (err) {
            done(err);
        });
});