Chai fails to test async express route function

旧巷老猫 提交于 2019-12-11 18:22:39

问题


I have been trying to test my Express routes using chai and mocha. I manage to get normal tests done but it failing on async function. test case:

describe('/Login wrong user', () => {
        it('It should attempt a login POST but with no data', (done) => {
            chai.request(app)
                .post('/login')
                .send({})
                .then((res) => {
                    expect(res).to.have.status(200);
                    done();
                }).catch((err) => {
                    throw err;
                });
        });
    });

The code I want to test

router.post('/', async function(req, res, next) {
    if (!req.body) return res.sendStatu(400);
    if (!req.body.usr) return res.sendStatus(400);
    if (!req.body.psw) return res.sendStatus(400);
    let user = new _USER();
    await user.login_user(req.body.usr, req.body.psw).then(ret => {
        if (ret === false) return res.sendStatus(401);
        req.session.active = true;
        req.session.user = ret;
        res.sendStatus(200);
    }).catch(err => {
        _UTILS.errorHandler(err, false, true);
        res.sendStatus(500);
    });
});

Stacktrace:

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

来源:https://stackoverflow.com/questions/50311710/chai-fails-to-test-async-express-route-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!