Skip to content

Commit

Permalink
fix: emit a connect_error event upon connection failure
Browse files Browse the repository at this point in the history
  • Loading branch information
darrachequesne committed Jan 5, 2021
1 parent b83f89c commit 53c7374
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/socket.ts
Expand Up @@ -84,6 +84,7 @@ export class Socket extends Emitter {
this.subs = [
on(io, "open", this.onopen.bind(this)),
on(io, "packet", this.onpacket.bind(this)),
on(io, "error", this.onerror.bind(this)),
on(io, "close", this.onclose.bind(this)),
];
}
Expand Down Expand Up @@ -204,6 +205,18 @@ export class Socket extends Emitter {
}
}

/**
* Called upon engine or manager `error`.
*
* @param err
* @private
*/
private onerror(err: Error) {
if (!this.connected) {
super.emit("connect_error", err);
}
}

/**
* Called upon engine `close`.
*
Expand Down
25 changes: 25 additions & 0 deletions test/socket.ts
Expand Up @@ -50,6 +50,31 @@ describe("socket", function () {
}, 300);
});

it("fire a connect_error event when the connection cannot be established", (done) => {
const socket = io("http://localhost:9823", {
forceNew: true,
timeout: 100,
});
socket.on("connect_error", () => {
socket.close();
done();
});
});

it("doesn't fire a connect_error event when the connection is already established", (done) => {
const socket = io({ forceNew: true });
socket.on("connect", () => {
socket.io.engine.close(true);
});
socket.on("connect_error", () => {
done(new Error("should not happen"));
});
setTimeout(() => {
socket.close();
done();
}, 300);
});

it("should change socket.id upon reconnection", (done) => {
const socket = io({ forceNew: true });
socket.on("connect", () => {
Expand Down

0 comments on commit 53c7374

Please sign in to comment.