如何使用 Jest 和 react-testing-library 测试 Websocket 客户端 [英] How to test Websocket Client with Jest and react-testing-library

查看:37
本文介绍了如何使用 Jest 和 react-testing-library 测试 Websocket 客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 create-react-app、Jest 和 react-testing-library 来配置聊天机器人项目.

我有一个 React 功能组件,它连接到 WebSocket 服务器,并且 DOM 会根据 WebSocket 消息进行更改,例如

const LiveChat = () =>{const [socket, setSocket] = useState(null)useEffect(() => {setSocket(new WebSocket('ws://localhost:1234'))}, [])useEffect(() => {插座&&socket.onmessage = 消息 =>{ handleAgentMessages(message.data) }}, [插座])const handleAgentMessages = 消息 =>{const { messageContent, messageType, secureKey } = JSON.parse(message)if (messageType === TEXT && messageContent) {警报(消息内容)playChatMessageSound()}...}返回 (<div className='live-chat' data-testid='live-chat'>...

)}

我想测试何时出现 TEXT 消息,是否出现警告框并带有 conteining 消息等.我浏览了互联网,发现 jest-websocket-mock 库,但似乎我也需要用这个库来模拟客户端,但我只想模拟服务器并期望客户端连接模拟 WebSocket 服务器,你有什么想法吗?

解决方案

我不确定这是否正确.但这对我有用,

 global.sendMsg = null;global.WebSocket = 类扩展 WebSocket {构造函数(网址){super(wss://test");global.sendMsg = null}addEventListener(event, cb) {如果(事件 ===打开"){cb();} else if(event ===消息"){global.sendMsg = cb;}}};测试(测试消息",()=> {渲染(<LiveChat/>);global.sendMsg({data:"test-msg"});预计....})

基本上,我重写了 WebSocket 类并将消息事件回调存储为一个常量,并在测试时触发它以模仿服务器消息.

I'm using create-react-app, Jest and react-testing-library for the configuration of the chatbot project.

I have a React functional component that connects to a WebSocket server and DOM changes according to WebSocket messages, for example

const LiveChat = () => {
  const [socket, setSocket] = useState(null)

   useEffect(() => {
    setSocket(new WebSocket('ws://localhost:1234'))
   }, [])

  useEffect(() => {
    socket && socket.onmessage = message => { handleAgentMessages(message.data) }
  }, [socket])

  const handleAgentMessages = message => {
     const { messageContent, messageType, secureKey } = JSON.parse(message)
     if (messageType === TEXT && messageContent) {
       alert(messageContent)
       playChatMessageSound()
     }
       ...
   }

   return (
      <div className='live-chat' data-testid='live-chat'>
          ...
      </div>
   )
}

I want to test when a TEXT message comes, is alertbox appeared with conteining message etc. I have looked through the internet and I find jest-websocket-mock library, but it seems that I need to mock the client with this library as well, but I just want to mock server and expect the client to connect the mocked WebSocket server, do you have any ideas?

解决方案

I am not sure if this is the right way or not. But this works for me,

    global.sendMsg = null;
    global.WebSocket = class extends WebSocket {
        constructor(url) {
            super("wss://test");
            global.sendMsg = null
        }
    
        addEventListener(event, cb) {
            if (event === "open") {
                cb();
            } else if(event === "message") {
                global.sendMsg = cb;
            }
        }
    };

    test("testing message",() => {
      render(<LiveChat />);
      global.sendMsg({data:"test-msg"});
 
      expect....
    })

Basically, I overwrote the WebSocket class and stored the message event callback to a constant, and trigger it on the tests to imitate the server message.

这篇关于如何使用 Jest 和 react-testing-library 测试 Websocket 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆