Skip to content

Commit

Permalink
reconnect: Simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
sonnyp committed Jan 8, 2025
1 parent 8ad2205 commit 8337bcc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 34 deletions.
16 changes: 7 additions & 9 deletions packages/reconnect/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ class Reconnect extends EventEmitter {
this._timeout = null;
}

#onDisconnect = () => {
this.scheduleReconnect();
};

scheduleReconnect() {
const { entity, delay, _timeout } = this;
clearTimeout(_timeout);
Expand Down Expand Up @@ -38,18 +42,12 @@ class Reconnect extends EventEmitter {

start() {
const { entity } = this;
const listeners = {};
listeners.disconnect = () => {
this.scheduleReconnect();
};

this.listeners = listeners;
entity.on("disconnect", listeners.disconnect);
entity.on("disconnect", this.#onDisconnect);
}

stop() {
const { entity, listeners, _timeout } = this;
entity.removeListener("disconnect", listeners.disconnect);
const { entity, _timeout } = this;
entity.removeListener("disconnect", this.#onDisconnect);
clearTimeout(_timeout);
}
}
Expand Down
49 changes: 24 additions & 25 deletions packages/reconnect/test.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,37 @@
import _reconnect from "./index.js";
import { EventEmitter } from "@xmpp/events";
// eslint-disable-next-line n/no-extraneous-import
import Connection from "@xmpp/connection";

test("it schedule a reconnect when disconnect is emitted", (done) => {
const entity = new EventEmitter();
test("schedules a reconnect when disconnect is emitted", () => {
const entity = new Connection();
const reconnect = _reconnect({ entity });
const spy_scheduleReconnect = jest.spyOn(reconnect, "scheduleReconnect");

reconnect.scheduleReconnect = () => {
expect.pass();
done();
};

expect(spy_scheduleReconnect).toHaveBeenCalledTimes(0);
entity.emit("disconnect");
expect(spy_scheduleReconnect).toHaveBeenCalledTimes(1);
});

test("#reconnect", async () => {
expect.assertions(3);

const entity = new EventEmitter();
const service = "service";
const lang = "lang";
const domain = "domain";

const entity = new Connection({
service,
lang,
domain,
});
const reconnect = _reconnect({ entity });

entity.options = {
service: "service",
lang: "lang",
domain: "domain",
};

entity.connect = (service) => {
expect(service).toBe(entity.options.service);
};

entity.open = ({ domain, lang }) => {
expect(domain).toBe(entity.options.domain);
expect(lang).toBe(entity.options.lang);
};
const spy_connect = jest.spyOn(entity, "connect").mockResolvedValue();
const spy_open = jest.spyOn(entity, "open").mockResolvedValue();

await reconnect.reconnect();

expect(spy_connect).toHaveBeenCalledWith(service);
expect(spy_open).toHaveBeenCalledWith({
domain,
lang,
});
});

0 comments on commit 8337bcc

Please sign in to comment.