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

如何在React本地环境中测试Azure通信库的网络诊断功能?

问题描述

我按照Azure通信服务的用户端诊断文档实现了代码,运行在本地环境,想要测试断网场景下显示「Network not available」提示,但目前断网时事件并未触发。以下是我的代码:

CallScreen组件代码

import {networkDiagnostics} from '../common/NetworkDiagnostics';
import {Features} from '@azure/communication-calling';

const CallScreen = () => {
    const userFacingDiagnostics = call?.feature(Features.UserFacingDiagnostics)
    React.useEffect(() => {    
      const netErr = userFacingDiagnostics?.network.on('diagnosticChanged', networkDiagnostics);
    }, [userFacingDiagnostics]);
}

NetworkDiagnostics文件代码

import { useState } from 'react';
import { NetworkDiagnosticChangedEventArgs, DiagnosticQuality, Features } from '@azure/communication-calling';

export const networkDiagnostics = (
  diagnosticInfo: NetworkDiagnosticChangedEventArgs
) => {
  const [networkQualityMessage, setNetworkQualityMessage] = useState('');
  console.log(`Diagnostic changed: ` +
    `Diagnostic: ${diagnosticInfo.diagnostic}` +
    `Value: ${diagnosticInfo.value}` +
    `Value type: ${diagnosticInfo.valueType}`);

  if (diagnosticInfo.valueType === 'DiagnosticQuality') {
    switch (diagnosticInfo.diagnostic) {
      case 'networkReconnect':
        if (diagnosticInfo.value === DiagnosticQuality.Poor) {
          setNetworkQualityMessage('Poor Network');
        } else if (diagnosticInfo.value === DiagnosticQuality.Bad) {
          setNetworkQualityMessage('Network is disconnected');
        } else if (diagnosticInfo.value === DiagnosticQuality.Good) {
          setNetworkQualityMessage('Network is connected');
        }
        break;
      case 'networkReceiveQuality':
        if (diagnosticInfo.value === DiagnosticQuality.Poor) {
          setNetworkQualityMessage('Poor Network');
        } else if (diagnosticInfo.value === DiagnosticQuality.Bad) {
          setNetworkQualityMessage('Problem with Network');
        } else if (diagnosticInfo.value === DiagnosticQuality.Good) {
          setNetworkQualityMessage('Network is connected');
        }
        break;
    }
  } else if (diagnosticInfo.valueType === 'DiagnosticFlag') {
    switch (diagnosticInfo.diagnostic) {
      case 'noNetwork':
        if (diagnosticInfo.value === true) {
          setNetworkQualityMessage('No Network available');
        } else if (diagnosticInfo.value === false) {
          setNetworkQualityMessage('Network available');
        }
        break;
      case 'networkRelaysNotReachable':
        if (diagnosticInfo.value === true) {
          setNetworkQualityMessage('Internet connection is fluctuating.');
        } else if (diagnosticInfo.value === false) {
          setNetworkQualityMessage('Stable internet connection is available');
        }
        break;
    }
  }

  return networkQualityMessage
}

请问我该如何在本地测试断网场景?或者我的代码是否遗漏了某些内容?


解决方案

一、代码存在的核心问题

  1. useState不能在普通函数中使用
    networkDiagnostics是普通工具函数,不是React组件或自定义钩子,直接调用useState违反React规则,状态更新不会生效,也无法关联组件渲染。必须把状态管理移到CallScreen组件内部,或把networkDiagnostics改为自定义钩子。

  2. 事件订阅未清理
    原代码未在组件卸载/依赖变化时取消事件订阅,会导致内存泄漏,需添加清理逻辑。

  3. 状态未在组件中渲染
    原函数返回的消息没有在CallScreen的JSX中输出,即使逻辑正确也看不到提示。

修改后的CallScreen组件示例

import { useState, useEffect } from 'react';
import { Features, NetworkDiagnosticChangedEventArgs, DiagnosticQuality } from '@azure/communication-calling';

const CallScreen = () => {
    const userFacingDiagnostics = call?.feature(Features.UserFacingDiagnostics);
    const [networkQualityMessage, setNetworkQualityMessage] = useState('');

    const handleNetworkDiagnosticChange = (diagnosticInfo: NetworkDiagnosticChangedEventArgs) => {
        console.log(`Diagnostic changed: ` +
            `Diagnostic: ${diagnosticInfo.diagnostic}` +
            `Value: ${diagnosticInfo.value}` +
            `Value type: ${diagnosticInfo.valueType}`);

        if (diagnosticInfo.valueType === 'DiagnosticQuality') {
            switch (diagnosticInfo.diagnostic) {
                case 'networkReconnect':
                    if (diagnosticInfo.value === DiagnosticQuality.Poor) {
                        setNetworkQualityMessage('Poor Network');
                    } else if (diagnosticInfo.value === DiagnosticQuality.Bad) {
                        setNetworkQualityMessage('Network is disconnected');
                    } else if (diagnosticInfo.value === DiagnosticQuality.Good) {
                        setNetworkQualityMessage('Network is connected');
                    }
                    break;
                case 'networkReceiveQuality':
                    if (diagnosticInfo.value === DiagnosticQuality.Poor) {
                        setNetworkQualityMessage('Poor Network');
                    } else if (diagnosticInfo.value === DiagnosticQuality.Bad) {
                        setNetworkQualityMessage('Problem with Network');
                    } else if (diagnosticInfo.value === DiagnosticQuality.Good) {
                        setNetworkQualityMessage('Network is connected');
                    }
                    break;
            }
        } else if (diagnosticInfo.valueType === 'DiagnosticFlag') {
            switch (diagnosticInfo.diagnostic) {
                case 'noNetwork':
                    setNetworkQualityMessage(diagnosticInfo.value ? 'No Network available' : 'Network available');
                    break;
                case 'networkRelaysNotReachable':
                    setNetworkQualityMessage(diagnosticInfo.value ? 'Internet connection is fluctuating.' : 'Stable internet connection is available');
                    break;
            }
        }
    };

    useEffect(() => {    
        if (!userFacingDiagnostics) return;
        // 订阅事件
        const subscription = userFacingDiagnostics.network.on('diagnosticChanged', handleNetworkDiagnosticChange);
        // 组件卸载时取消订阅
        return () => subscription?.off();
    }, [userFacingDiagnostics]);

    // 在界面中渲染提示消息
    return (
        <div className="call-screen">
            {networkQualityMessage && <div className="network-alert">{networkQualityMessage}</div>}
            {/* 其他通话界面元素 */}
        </div>
    )
}

二、本地断网测试方法

  1. 系统级断网测试
    直接断开本地网络(关闭WiFi、禁用网卡),注意:Azure通信服务的noNetwork诊断需要几秒检测延迟,不要立即判定事件未触发。

  2. 浏览器开发者工具模拟断网

  • 打开Chrome/Firefox开发者工具(F12)
  • 切换到「Network」面板
  • 勾选「Offline」选项(Chrome在面板顶部,Firefox在「网络状态」下拉菜单)
  • 保持工具打开,浏览器会模拟完全断网,触发noNetwork事件。
  1. 手动模拟事件测试
    如果想直接验证提示逻辑,可在组件中添加测试按钮,手动触发诊断事件:
<button onClick={() => {
    handleNetworkDiagnosticChange({
        diagnostic: 'noNetwork',
        value: true,
        valueType: 'DiagnosticFlag'
    } as NetworkDiagnosticChangedEventArgs);
}}>模拟断网</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 02:07:36