#Jest Error Expected: { _id:1} but Received: {_id: "undefined"} while unit testing jwt.helper.js file

3 messages · Page 1 of 1 (latest)

hallow hatch
#

I tried to figure out why the test fails for the jwt.helper.js file. But, unable to find the cause of it.

[file: jwt.helper.js]

const jwt = require('jsonwebtoken');
exports.generateJwtToken = (userObj) => {
  const token = jwt.sign({ _id: userObj._id }, process.env.JWT_SECRET, {
    algorithm: 'HS512',
    expiresIn: '1d',
  });
  return token;
};

[file: jwt.helper.test.js]

const jwt = require('jsonwebtoken');
const { generateJwtToken, verifyJwtToken } = require("../../../helpers/jwt.helper");
jest.mock('jsonwebtoken', () => ({
  sign: jest.fn(),
  verify: jest.fn(),
}));

describe("Unit tests for jwt.helper.js file", () => {
  it('generates a JWT token correctly', () => {
    //Arrange
    const userObj = { _id: 1, name: 'testuser', email: '[email protected]' };
    const jwtSecretKey = 'supersecret';
    const jwtOptions = { option_key1: "option_value1", option_key2: "option_value2" };
    const token = "jsontoken";

    const signSpy = jest.spyOn(jwt, 'sign').mockReturnValue(token);

    //Act
    const result = generateJwtToken(userObj);

    //Assert
    expect(result).toBe(token);
    expect(signSpy).toHaveBeenCalledWith({ _id: userObj._id }, jwtSecretKey, jwtOptions);
  });
});

[Output]

- Expected
    + Received

      Object {
    -   "_id": 1,
    +   "_id": undefined,
      },
    - "supersecret",
    + undefined,
      Object {
    -   "option_key1": "option_value1",
    -   "option_key2": "option_value2",
    +   "algorithm": "HS512",
    +   "expiresIn": "1d",
      },
Number of calls: 1

  22 |     //Assert
  23 |     expect(result).toBe(token);
> 24 |     expect(signSpy).toHaveBeenCalledWith({ _id: userObj._id }, jwtSecretKey, jwtOptions);
     |                     ^
  25 |   });
  26 |
  27 |   it('verifies a JWT token correctly', () => {
  at Object.<anonymous> (__tests__/unit/helpers/jwt.helper.test.js:24:21)

I wanted to write the test for the generateJwtToken function.

vapid blaze
#

looks like a real test failure? data being passed in doesn't match what the test instructs it to expect

#

in which case, answering "why is this broken" is very much The Work, don't think we'll be able to answer