dimanche 27 janvier 2019

unit testing async express middleware

I have the following async middleware which uses multiple try-catches to check for the response of some http calls. I wish to unit test this middleware but am encountering difficulties mocking the "next" callback. When i wrap it like so:

it('should test for auth', () => {
    logon(req, res, function() {
        expect(res.locals).toBe(true)
    })
})

it does not seem to be actually running the function and running the expect after. Any ideas on how I can mock the request, response and next objects so I can test for the final values (res.locals)? Thanks.

async function logon(req, res, next) {

if (!req.query.isAuth)
    req.locals.auth = false;
    next()
}

try {
    const getData = await http.get(/logon);
    if (getData.status == 200) {
        res.locals.auth = true;
    } else {
        res.locals.auth = false;
        try {
            const secondCall = http.get(/logon2);
            if (secondCall.data.bob) {
                return res.redirect(/home);
            }
        } catch(e) {console.error(3)}
    }
} catch(e) {console.error(e)}
next();
}

Aucun commentaire:

Enregistrer un commentaire