单元测试 jwt.helper.js 文件时预计出现 Jest 错误:{_id:1} 但收到:{_id: "undefined"}

问题描述 投票:0回答:1

我试图找出 jwt.helper.js 文件测试失败的原因。但是,找不到原因。

[文件: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;
};

[文件: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);
  });
});

[输出]

- Expected
    + Received

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

通话次数: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)

我想为 generateJwtToken 函数编写测试,以便它可以调用 jsonwbtoken 模块的模拟版本。我想确保使用必要的参数调用该模块的 sign 函数。

unit-testing jestjs
1个回答
0
投票

模拟

userObj
变量使用
id
属性,而
generateJwtToken
期望参数具有
_id
属性。

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);
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.