From 37d3f7ab5f7b6059031e5e2e7214ac3da1275e57 Mon Sep 17 00:00:00 2001 From: Samlior Date: Wed, 8 Sep 2021 11:45:29 +0800 Subject: [PATCH] Fix unsubscribe and add a test (#4058) Co-authored-by: Alex Co-authored-by: Wyatt Barnes --- packages/web3-core-subscriptions/src/subscription.js | 2 +- test/eth.subscribe.ganache.js | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/web3-core-subscriptions/src/subscription.js b/packages/web3-core-subscriptions/src/subscription.js index b0b134d7997..e244c6d2bbb 100644 --- a/packages/web3-core-subscriptions/src/subscription.js +++ b/packages/web3-core-subscriptions/src/subscription.js @@ -281,7 +281,6 @@ Subscription.prototype.subscribe = function() { if(!err && result) { _this.id = result; _this.method = payload.params[0]; - _this.emit('connected', result); // call callback on notifications _this.options.requestManager.addSubscription(_this, function(error, result) { @@ -310,6 +309,7 @@ Subscription.prototype.subscribe = function() { _this.emit('error', error); } }); + _this.emit('connected', result); } else { setTimeout(function(){ _this.callback(err, false, _this); diff --git a/test/eth.subscribe.ganache.js b/test/eth.subscribe.ganache.js index 82c47ff6fba..1b1b910aa7e 100644 --- a/test/eth.subscribe.ganache.js +++ b/test/eth.subscribe.ganache.js @@ -54,6 +54,18 @@ describe('subscription connect/reconnect', function () { }); }); + it('unsubscribe should remove the subscription object from the subscriptions and send eth_unsubscribe to the node', function (done) { + subscription = web3.eth + .subscribe('newBlockHeaders') + .on('connected', function () { + const id = subscription.id; + assert(subscription.options.requestManager.subscriptions.has(id)); + subscription.unsubscribe(); // Send eth_unsubscribe to the node + assert(!subscription.options.requestManager.subscriptions.has(id)); + done(); + }); + }); + it('clearSubscriptions', async function() { web3.eth.subscribe('newBlockHeaders'); await waitSeconds(1); // Sub need a little time to set up