如何使用jest/react-testing-library模拟 socket.io 客户端



我正在构建一个聊天应用程序,想使用react-testing-library编写集成测试,但不知道如何模拟socket.io-clientsocket.onsocket.emit等。

我尝试按照这篇文章进行操作,并尝试使用 mock-socket.io 和 socket.io 模拟,但没有运气。

这是我正在尝试测试的组件:

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;

这是一个较晚的答案,但可能对其他人有用:

为了模拟socket.io-client库,我使用了jest mock函数并使用了第三方库socket.io-mockhttps://www.npmjs.com/package/socket.io-mock

您需要按如下方式修改连接函数才能使用模拟套接字:

const url= process.env.NODE_ENV==='test'?'':`http://localhost:${port}`;
const socket = io(url);

实现:

import socketIOClient from 'socket.io-client';
import MockedSocket from 'socket.io-mock';
jest.mock('socket.io-client');
describe('Testing connection', () => {
let socket;
beforeEach(() => {
socket = new MockedSocket();
socketIOClient.mockReturnValue(socket);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('should dispatch connect event', () => {
/*socket should connect in App and 
Note that the url should be dummy string 
for test environment e.g.(const socket = io('', options);)*/
const wrapper = (
<Provider store={store}>
<App />
</Provider>
);
expect(socketIOClient.connect).toHaveBeenCalled();
});
it('should emit message:new', done  => {
const wrapper = (
<Provider store={store}>
<App />
</Provider>
);
...
socket.on('message:new', (data)=>{
expect(data).toEqual(['message1', 'message2']);
done();
});
socket.socketClient.emit('message:new', ['message1', 'message2']);
...
});
});

相关内容

  • 没有找到相关文章

最新更新