Hello everyone,
I created websocket_mock - a library to test WebSocket based interfaces of clients and servers.
It allows to preconfigure a web server with responses based on the messages it receives. You can also send messages to individual clients without receiving a message first. The library also includes a small WebSocket client which is just a thin wrapper around WebSockex with some utility methods for testing. It’s useful when you need to assert that multiple clients received messages.
defmodule MyAppTest do
use ExUnit.Case
alias WebSocketMock.MockServer
alias WebSocketMock.MockClient
setup do
{:ok, server} = MockServer.start()
on_exit(fn -> MockServer.stop(server) end)
%{server: server}
end
test "manual interaction", %{server: server} do
{:ok, client} = MockClient.start(server.url)
[%{client_id: client_id}] = MockServer.list_clients(server)
MockServer.send_message(server, client_id, {:text, "Hello!"})
assert MockClient.received_messages(client) == [{:text, "Hello!"}]
MockClient.send_message(client, {:text, "world"})
assert {:text, "world"} in MockServer.received_messages(server, client_id)
end
test "auto-replies", %{server: server} do
MockServer.reply_with(server, {:text, "ping"}, {:text, "pong"})
# Responds to any message that is exactly "secret"
MockServer.reply_with(server, fn {_op, msg} -> msg == "secret" end, {:text, "unlocked"})
# Uses the incoming message to construct the reply
MockServer.reply_with(server, "echo", fn {op, msg} -> {op, msg <> " pong"} end)
{:ok, client} = MockClient.start(server.url)
MockClient.send_message(client, {:text, "ping"})
Process.sleep(20)
assert {:text, "pong"} in MockClient.received_messages(client)
MockClient.send_message(client, {:text, "secret"})
Process.sleep(20)
assert {:text, "unlocked"} in MockClient.received_messages(client)
MockClient.send_message(client, {:text, "echo"})
Process.sleep(20)
assert {:text, "echo pong"} in MockClient.received_messages(client)
end
end
Feedback and contributions are always welcome!






















