1

I'm trying to create a test that will test the following branch.

if (req.body.sessionToken) {
  let sessionToken = req.body.sessionToken;
  let tokenData = jwt.verify(sessionToken,config.secretSessionKey);
  sessionID = tokenData.sessionID;
}

I tried creating a mock JSON response containing a sessionToken key with a random value that will be sent but I'm getting a UnauthorizedError: jwt malformed error. I believe that I only have to provide the mock sessionToken in the right format to run the test since based on the test coverage, I'm getting the error on the

let sessionTokenData = jwt.verify(sessionToken,config.secretSessionKey);

but I have to idea how should it be written.

Here is a part of my test. I'm calling the /authenticate endpoint then sending the sessionToken JSON that will contain the mock sessionToken value.

 return request
  .post("/authenticate")
  .send(sessionToken)
  .then(response => {
    let body = JSON.parse(response.text); })
McD
  • 29
  • 5
  • What does your test look like? – Christian Nov 15 '21 at 07:47
  • edited the question and added a part of my test – McD Nov 15 '21 at 07:55
  • You can mock `jwt.verify` method altogether, since it is a library method and was tested already – ivanjermakov Nov 15 '21 at 08:00
  • how can I mock it all at once? and will it still cover the branch since it needs the req.body.sessionToken? – McD Nov 15 '21 at 08:05
  • `I tried creating a mock JSON response containing a sessionToken key` - how are you creating the JWT which is in the `sessionToken` field? – Michal Trojanowski Nov 15 '21 at 08:21
  • here is the mock req I created: "sessionToken": { "userEmail": "test@gmail.com", "userPassword": "12345678", "sessionId": "95ce5656-605d-42d5-9119-a82ef312325d", "sessionToken":"eyJhbGciOiJSUzI1NiIsIng1dCI6IjdkRC1nZWNOZ1gxWmY3R0xrT3ZwT0IyZGNWQSIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL2NvbnRvc28uY29tIiwiaXNzIjoia" } – McD Nov 15 '21 at 08:32
  • did you just show a shortened token in the comment or is your session token exactly like this in your code? If you used exactly this token, then the *jwt malformed error* should be no surprise, because it is malformed – jps Nov 15 '21 at 09:19
  • it is a shortened one since there is a char limit in the comments but I'm using a working token as a mock – McD Nov 15 '21 at 09:21

0 Answers0