A demonstration app showcasing how to implement real-time WebSocket communication with Mock Service Worker (MSW). This example is ideal for learning how to mock WebSocket interactions and build dynamic chat functionality in a controlled development environment.
The application uses MSW to mock WebSocket connections. The mock server is automatically initialized in the example wrapper
// const wssUri = 'wss://onurdayibasi.dev'
// src/mocks/handlers.js
import { ws } from "msw";
import { wssUri } from "../server/api-uris";
const chat = ws.link(wssUri);
export const wsHandlers = [
chat.addEventListener("connection", ({ client }) => {
client.addEventListener("message", (event) => {
client.send(event.data);
});
}),
];
ChatApp is an UI App which uses Websocket connections
const ws = new WebSocket(wssUri);
React.useEffect(() => {
const handleMsg = (event) => {
addResponse({ role: "user", content: event.data });
};
ws.addEventListener("message", handleMsg);
return () => {
ws.removeEventListener("message", handleMsg);
};
}, []);
///
///
<Button
type="primary"
shape="circle"
icon={<ArrowCircleUp size={42} />}
onClick={() => ws.send(value)}
/>;