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

Jest环境下TypeScript应用SignalR协商失败:TypeError: fetch failed问题解决

解决Jest中Azure SignalR协商失败问题

问题背景

我们在开发机上运行Azure Function App(地址:http://localhost:7071/api),其negotiate端点指向Azure Serverless SignalR实例。功能类似的.NET测试应用能正常完成协商,但TypeScript代码在Jest中运行时始终无法完成协商,且Azure Function的C#negotiate端点断点从未触发。

Azure Function App配置

"Host": {
    "LocalHttpPort": 7071,
    "CORS": "*"
}

TypeScript协商逻辑代码

const options: IHttpConnectionOptions = {
    accessTokenFactory: () => '',
    logger: this.logger,
    logMessageContent: true,
    headers: { 
        'x-ms-signalr-userid' : 'myuserid',
        'x-functions-key' : 'myfunckey'
    }
}; 
this.hubConnection = new signalR.HubConnectionBuilder()
    .withUrl(`http://localhost:7071/api`, options)
    .configureLogging(LogLevel.Information)
    .withAutomaticReconnect()
    .build();

this.hubConnection.start().then(() => {
    this.logger?.log(LogLevel.Information, "Hub connection established.");
    resolve(true);
})
.catch(error => {
    this.logger?.log(LogLevel.Critical, `Unable to establish a connection to the hub. The start failed: ${error}`);
    reject(false);
});

依赖配置

"dependencies": {
    "@microsoft/signalr": "^7.0.5",
    "rxjs": "^7.8.0",
    "typescript": "~4.9.5"
}

报错信息

Failed to complete negotiation with the server: TypeError: fetch failed

解决方案建议

  • 修复Jest环境的fetch支持:Jest默认Node.js环境没有内置浏览器fetch API,@microsoft/signalr依赖该API。安装cross-fetch并全局注入:

    npm install cross-fetch --save-dev
    

    在测试文件顶部添加:

    import crossFetch from 'cross-fetch';
    global.fetch = crossFetch;
    
  • 修正连接URL格式:Serverless SignalR的Function端点需包含Hub名称,正确格式为http://localhost:7071/api/{hubName}。修改withUrl参数:

    .withUrl(`http://localhost:7071/api/yourHubName`, options)
    
  • 验证Functions Key有效性:本地运行Azure Function若未启用API密钥验证,可暂时移除x-functions-key头信息测试:

    headers: { 
        'x-ms-signalr-userid' : 'myuserid'
        // 'x-functions-key' : 'myfunckey'
    }
    
  • 检查网络访问权限:确认Jest测试环境能正常访问localhost:7071。若使用WSL,改用主机IP(如http://192.168.x.x:7071/api)尝试连接。

  • 启用详细日志排查:将日志级别调至Trace获取更多错误细节:

    .configureLogging(LogLevel.Trace)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 18:50:09