我建立一个聊天应用程序,并会使用喜欢写集成测试react-testing-library
并不能弄清楚如何嘲笑socket.io-client
的socket.on
,socket.emit
等等。
我尝试按照这篇文章并尝试使用mock-socket.io和socket.io-mock都没有运气。
这是我要测试的组件:
import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';
import 'dotenv/config';
import ChatInput from './ChatInput';
import Messages from './Messages';
function App() {
const [messages, setMessages] = useState([]);
const port = process.env.REACT_APP_SERVER_PORT;
const socket = io(`http://localhost:${port}`);
useEffect(() => {
socket
.emit('app:load', messageData => {
setMessages(messages => [...messages, ...messageData]);
})
.on('message:new', newMessage => {
setMessages(messages => [...messages, newMessage]);
});
}, []);
const postMessage = input => {
socket.emit('message:post', input);
};
return (
<div className="App">
<Messages messages={messages} />
<ChatInput postMessage={postMessage} />
</div>
);
}
export default App;