-
Notifications
You must be signed in to change notification settings - Fork 2
Testing
Nancy.AspNet.WebSockets extends Nancy.Testing so that you easily can test your websocket endpoints. Here's an example from Nancy.AspNet.WebSockets.Testing.Tests:
[Test]
public void Should_raise_opened_event_on_socket_instance()
{
var openCount = 0;
_browser.OpenWebSocket("/ws", socket =>
{
socket.Opened += (sender, args) =>
{
openCount++;
socket.Close();
};
});
Assert.That(openCount, Is.EqualTo(1));
}
The _browser
variable is a regular Nancy.Testing.Browser
instance. The test connects a websocket to the specified endpoint and closes it as soon as it is connected.
As you can see, the second argument to OpenWebSocket
is a configurator delegate/lambda that is used to setup the client-side part of the client-server interaction. The following events can be listened to:
- MessageReceived
- DataReceived
- Closed
- Opened
- Error
Note that the configuration code as well as code within event handles run on the test thread. The call to OpenWebSocket
will block until one of the following conditions occur:
- The websocket is closed by the client, i.e. within one of the event handlers.
- The websocket is closed by the server.
- A timeout occurs.
The default timeout is 3 seconds. The timeout can be changed when configuring the socket:
_browser.OpenWebSocket("/ws", socket => {
socket.MaxAge = TimeSpan.FromMilliseconds(200);
// ... more setup ...
});
It's not possible to send a message or binary data or close the socket until it has been connected. All socket interaction should take place within an event handler.
All server code, i.e. the code in the websocket handler returned by the websocket endpoint, will run on a separate Task.