Hitting connection limits while in development or testing with hot-reload in React

If you're in development mode, using hot-reload, you may make this issue even worse.

Hot reload replaces portions (or all) of your site during development mode. This is great for productivity - effectively "reloading" the browser tab, or portions of the browser tab, right in front of you.

 

If you hot-reload a React component (or just a webpage) that contains code that connects to Ably, your Ably connection will be rapidly disconnected and reconnected as part of the reload - if you have defined the Ably client inside the scope of your react component, you may find that you are opening lots of connections while you are developing and hot reload may rapidly use up your connection limits.

 

If you find this is happening to you during development - we'd recommend stubbing out the Ably SDK with a mock of some kind.

 

Mocking and stubbing in the browser, is when you create a new JavaScript object that matches the function signatures of our SDKs, but actually doesn't call Ably at all. Mocks and stubs are great for testing, as you can add your own logic to simulate messages, and capture the output of messages that would have been sent if you were using the real SDKs.

 

Here's an example of an stubbed implementation of Ably/Promises that can be used in tests, to verify the behaviour of Ably, and you could use to make sure you are not using up all your connection limits during development.

 

const fakeAblyChannel = {
published: [],
subscribe: function(callback) {
this.callback = callback;
},
publish: function(message) {
this.published.push(message);
this.callback(message);
}
}

class AblyStub {
fakeAblyChannel = fakeAblyChannel;
connection = { on: function(string) { } };
channels = { get: function(chName) { return fakeAblyChannel; } }
}

window.Ably = { Realtime: { Promise: AblyStub } };

 

This stub will push any messages that are sent to an internal array called published, and simulates a subscription to any Ably channel.

You can use this stub like our normal SDK for publishing and subscribing, and it'll mostly behave the same.