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

Mock jsonwebtoken decode方法返回null问题排查求助

解决jsonwebtoken decode方法Mock返回null的问题

问题根源

你的测试代码里重复调用了jest.mock('jsonwebtoken'),第一次空mock会覆盖后续的自定义mock配置,导致decode方法没有被正确模拟。此外,部分注释的写法存在逻辑错误(比如mockImplementation返回嵌套函数)。

修正后的测试代码

import jwt from 'jsonwebtoken'
// 移除重复的空jest.mock调用
jest.mock('jsonwebtoken', () => ({
    ...jest.requireActual('jsonwebtoken'), // 保留原包其他方法的功能
    decode: jest.fn().mockReturnValue({ aud: 'bar', data: { seller_code: 343 } }) // 模拟decode的返回值
}));

describe.only('EncryptData', () => {
    it('Should extract token', () => {
        process.env.REACT_APP_DEVELOPER = "Random value2";
        const res = TokenExtractor({ headers: { authorization: 'Bearer Token33432' } }, undefined, () => { })
        console.log(res)
        // 可添加断言验证调用逻辑
        expect(jwt.decode).toHaveBeenCalledWith('Token33432') // 假设TokenExtractor会提取出Bearer后的token字符串传入decode
        expect(res).toEqual(/* 填写你的预期返回结果 */)
    })
})

额外检查点

  • 确认TokenExtractor中是否正确从Authorization头提取token:必须去掉Bearer 前缀,将纯token字符串传入jwt.decode。如果提取的token为空或格式错误,即使mock正确,业务逻辑也可能出现异常。
  • 若项目中使用命名导入import { decode } from 'jsonwebtoken',当前的mock写法依然适用,无需额外调整结构。

内容的提问来源于stack exchange,提问作者Rohit Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:55:20