You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest测试jwt.helper.js失败:预期{_id:1}却得到{_id:undefined}

解决Jest测试JWT生成函数的断言失败问题

问题根源

测试断言失败的核心原因是测试用例的预期与实际代码逻辑不匹配,具体有三点:

  • 第一个参数:测试传入的用户对象属性是id,但实际代码中取的是userObj._id,导致_id值为undefined
  • 第二个参数:实际代码依赖process.env.JWT_SECRET生成密钥,但测试未设置该环境变量,导致密钥为undefined
  • 第三个参数:测试期望传入自定义配置项,但实际代码固定使用{algorithm: 'HS512', expiresIn: '1d'}作为配置

修复方案

修改测试代码,让预期与实际代码逻辑对齐:

1. 修正用户对象的属性名

将测试中的userObj属性从id改为_id,匹配代码中的取值逻辑:

const userObj = { _id: 1, name: 'testuser', email: 'test@test.com' };

2. 设置测试环境变量

在测试的Arrange阶段添加环境变量设置,确保process.env.JWT_SECRET有值:

process.env.JWT_SECRET = 'supersecret';

3. 修正断言的配置参数

将断言中的jwtOptions替换为实际代码使用的固定配置:

const jwtOptions = { algorithm: 'HS512', expiresIn: '1d' };

修改后的完整测试代码

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: 'test@test.com' };
    const jwtSecretKey = 'supersecret';
    const jwtOptions = { algorithm: 'HS512', expiresIn: '1d' };
    const token = "jsontoken";

    // 设置环境变量
    process.env.JWT_SECRET = jwtSecretKey;
    
    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);
  });
});

内容的提问来源于stack exchange,提问作者Nilesh Sanyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 14:18:22