vendredi 9 juin 2017

How to test a function which consumes a callback? Or how to defer the assertion?

I use Jest to test a function which generates a JSON Web Token. It seems that I can't assert the value since when I assert, the callback hasn't been executed yet.

const issueJWT = function issueJWT(req, res, next) {
    jwt.sign(signUser, function (err, token) {
        if (err) {
            next(err);
            return;
        }
        res.locals.token = token;
        next();
    });
};

This is my test, I mock the request and response, then assert the result:

test('Should return a JWT with proper value if nothing wrong happened', () => {
    issueJWT(request, response, mockNext);

    const JWT = response.locals.token;
    const tokenPayload = jwt.decode(JWT, { complete: true }).payload;
    expect(tokenPayload).toHaveProperty('iat');
    expect(tokenPayload).toHaveProperty('exp');
    expect(tokenPayload).toHaveProperty('id');
});

The error is:

TypeError: Cannot read property 'payload' of null

How to make it work? According to my knowledge, I think the callback is at the task queue which means it will be executed when nothing is in the event loop, right? I wanna find a way to defer my assertion, but don't know how...

Aucun commentaire:

Enregistrer un commentaire