简体   繁体   English

如何使用 Jest 和 react-testing-library 测试 Websocket 客户端

[英]How to test Websocket Client with Jest and react-testing-library

I'm using create-react-app, Jest and react-testing-library for the configuration of the chatbot project.我正在使用 create-react-app、Jest 和 react-testing-library 来配置聊天机器人项目。

I have a React functional component that connects to a WebSocket server and DOM changes according to WebSocket messages, for example例如,我有一个连接到 WebSocket 服务器的 React 功能组件,并且 DOM 会根据 WebSocket 消息进行更改

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?我想测试何时出现 TEXT 消息,是否出现带有 conteining 消息的警报框等。我浏览了互联网,找到了jest-websocket-mock库,但似乎我也需要用这个库来模拟客户端,但我只想模拟服务器并期望客户端连接模拟的 WebSocket 服务器,您有什么想法吗?

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.基本上,我覆盖了 WebSocket 类并将消息事件回调存储为一个常量,并在测试中触发它以模仿服务器消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM