From cbee62e9b1e3878b96e7c3b7378e203a2a8d7063 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Tue, 2 Jul 2024 21:13:40 +0800 Subject: [PATCH] fix: don't close used mock agent avoid ClientDestroyedError ```bash ClientDestroyedError: The client is destroyed at Agent.dispatch (node_modules/undici/lib/dispatcher-base.js:172:15) at MockAgent.dispatch (node_modules/undici/lib/mock/mock-agent.js:65:25) at MockAgent.request (node_modules/undici/lib/api/api-request.js:169:10) ``` --- index.js | 5 ++--- lib/mock_agent.js | 20 ++++++++------------ 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/index.js b/index.js index 6382895..ab1b4ca 100644 --- a/index.js +++ b/index.js @@ -22,9 +22,8 @@ module.exports.default = mock; Object.assign(mock, mm, { restore() { cluster.restore(); - mm.restore(); - // return promise - return mockAgent.restore(app); + mockAgent.restore(app); + return mm.restore(); }, /** diff --git a/lib/mock_agent.js b/lib/mock_agent.js index 9eeba0d..1195973 100644 --- a/lib/mock_agent.js +++ b/lib/mock_agent.js @@ -8,12 +8,10 @@ module.exports = { getAgent(app) { if (!_global) { _global = getGlobalDispatcher(); - if (typeof app?.httpclient?.getDispatcher === 'function') { - if (!app[APP_HTTPCLIENT_AGENT]) { - // save the raw dispatcher - app[APP_HTTPCLIENT_AGENT] = app.httpclient.getDispatcher(); - } - } + } + if (!app[APP_HTTPCLIENT_AGENT] && typeof app?.httpclient?.getDispatcher === 'function') { + // save the raw dispatcher + app[APP_HTTPCLIENT_AGENT] = app.httpclient.getDispatcher(); } if (!_mockAgent) { _mockAgent = new MockAgent(); @@ -24,16 +22,14 @@ module.exports = { } return _mockAgent; }, - async restore(app) { + restore(app) { if (!_mockAgent) return; if (_global) { setGlobalDispatcher(_global); - if (app?.[APP_HTTPCLIENT_AGENT]) { - app.httpclient.setDispatcher(app[APP_HTTPCLIENT_AGENT]); - } } - const agent = _mockAgent; + if (app?.[APP_HTTPCLIENT_AGENT]) { + app.httpclient.setDispatcher(app[APP_HTTPCLIENT_AGENT]); + } _mockAgent = null; - await agent.close(); }, };