Repository navigation
Replies: 1 comment
|
A good approach is to mock the Socket.IO server, not the client. For local development, run a tiny local Socket.IO server on your machine and point the Flutter app to it. Your app code will still use the real client library, but the backend is a fake server that emits the same events your UI expects. Example with Node: const { Server } = require("socket.io");
const io = new Server(3000, {
cors: {
origin: "*"
}
});
io.on("connection", (socket) => {
console.log("client connected");
socket.emit("connected", { ok: true });
socket.on("join-room", (room) => {
socket.join(room);
io.to(room).emit("room-update", {
room,
users: 1
});
});
socket.on("send-message", (msg) => {
socket.broadcast.emit("new-message", {
user: "mock-user",
text: msg
});
});
});Then in Flutter: final socket = io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
socket.connect();
socket.on('connected', (data) {
print(data);
});
socket.emit('join-room', 'room-1');This is usually much better than trying to “fake” Socket.IO at the app layer, because you are testing the real protocol behavior. For unit tests, the usual pattern is:
Example idea: abstract class RealTimeService {
Stream<Map<String, dynamic>> get events;
void connect();
void emit(String event, dynamic data);
}Then your production implementation wraps the socket client, and your test implementation emits mocked events manually. So in short:
If you want, I can give you a small complete Flutter + Node mock server example for a typical chat or live status feature. |
Uh oh!
There was an error while loading. Please reload this page.
In flutter app I have added socket io because of a feature that needs real-time but problem is my api is not yet deployed so I want mock server to simulate real-time communication in rest api I can easily mock responses for any request but for socket io that is my question how I mock it for development and testing stages in flutter side
All reactions