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

NodeJS Azure Function中JEST mock JWT模块超时该如何解决?

问题原因

你触发超时的核心原因是mock实现和原模块的接口不匹配:

  • 原jwtDecoder是回调风格实现,接收3个参数:body、secret、回调函数cb,执行完成后会调用cb传递结果
  • 你当前的mock返回了Promise,完全没有调用传入的cb,导致业务代码里的回调逻辑永远不会触发,context.done()无法执行,最终超时
修复方案

调整jwtDecoder的mock实现,按照原接口的回调逻辑传递返回值即可,两种常见场景的mock写法如下:

1. 模拟JWT验证成功(返回200的场景)

直接调用回调函数的第一个参数传null,第二个参数传你模拟的解密后数据:

JWT.mockImplementation((body, secret, cb) => {
  // 第一个参数为错误对象,成功场景传null,第二个是解密后的jwt payload
  cb(null, { userId: 'test123', role: 'admin' })
})

2. 模拟JWT验证失败(返回400的场景)

调用回调函数时第一个参数传入错误对象即可:

JWT.mockImplementation((body, secret, cb) => {
  cb(new Error('invalid jwt signature'), null)
})
修改后的完整测试代码
let indexTest = require('../index')
const { runStubFunctionFromBindings } = require('stub-azure-function-context')

let JWT = require('../jwtDecoder')
jest.mock("../jwtDecoder.js")

beforeAll(() => {
    process.env = Object.assign(process.env, {
        NODE_ENV: "test",
        jwtsecret: "test-secret" // 补齐业务代码用到的环境变量
    });
});

describe('Simple Testing', () => {
    test('JWT验证正常时返回200', async() => {
        // mock验证成功的场景
        JWT.mockImplementation((body, secret, cb) => {
            cb(null, { userId: 'test' })
        })
        let request = {
            body: "dummy.jwt.zT5p"
        };
        const context = await runStubFunctionFromBindings(indexTest, [
            { type: 'httpTrigger', name: 'req', direction: 'in', data: request },
            { type: 'http', name: 'res', direction: 'out' },
        ], new Date());
        expect(context.res.status).toEqual(200);
    });

    test('JWT验证失败时返回400', async() => {
        // mock验证失败的场景
        const mockError = new Error('invalid jwt')
        JWT.mockImplementation((body, secret, cb) => {
            cb(mockError, null)
        })
        let request = {
            body: "invalid.jwt.token"
        };
        const context = await runStubFunctionFromBindings(indexTest, [
            { type: 'httpTrigger', name: 'req', direction: 'in', data: request },
            { type: 'http', name: 'res', direction: 'out' },
        ], new Date());
        expect(context.res.status).toEqual(400);
        expect(context.res.body.error.message).toEqual(mockError.message);
    });
});

内容的提问来源于stack exchange,提问作者Sharath Jallu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:06:01