Skip to content

Commit

Permalink
fix: don't close used mock agent
Browse files Browse the repository at this point in the history
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)
```
  • Loading branch information
fengmk2 committed Jul 2, 2024
1 parent 95666e1 commit cbee62e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 15 deletions.
5 changes: 2 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
},

/**
Expand Down
20 changes: 8 additions & 12 deletions lib/mock_agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
},
};

0 comments on commit cbee62e

Please sign in to comment.