boomchickawawa
boomchickawawa

Reputation: 556

Unable to mock a users access token from the request object and test the method

I am trying to unit test a method that creates a JWT and in the process I am trying to mock out the user's access token that would be used to create the JWT. Here is my method and the test:

returnToken(expressRequestObject) {
        const payload = { userAccessToken: req.user.userAccessToken, userID: req.params.userID};

        return jwt.sign(
            payload,
            SECRET,
            { expiresIn: '30d' },
        );
    }

Test Code:

describe('returns a token', function() {
        it('should return a token', function() {
            const requestObject = httpMocks.createRequest({params: {userID: '1234'}});
            requestObject.user.userAccessToken = 'xivjioefv.dvedv.adsvdv';

            const a = authenticatorClass.returnToken(requestObject);
            console.log(a);
        });

I am using httpMocks to create a mock request object. I am unable to make this test pass since it errors out saying TypeError: Cannot set property 'userAccessToken' of undefined. What am I doing wrong here? Is there a better way to mock out the access token and make this test pass? TIA

Upvotes: 0

Views: 542

Answers (1)

boomchickawawa
boomchickawawa

Reputation: 556

adding user object to this {{params: {userID: '1234'}},user: {userAccessToken: ''}} resolved this for me

Upvotes: 0

Related Questions