Skip to content

Commit

Permalink
fix: don't close used mock agent (#170)
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)
```

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Refactor**
- Improved the control flow in the `restore()` method to enhance
function execution order.
- Streamlined logic in agent management for better clarity and
efficiency.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
fengmk2 authored Jul 2, 2024
1 parent 95666e1 commit 3e7a504
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 14 deletions.
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ module.exports.default = mock;
Object.assign(mock, mm, {
restore() {
cluster.restore();
mm.restore();
mockAgent.restore(app);
// return promise
return 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?.httpclient?.[APP_HTTPCLIENT_AGENT] && typeof app?.httpclient?.getDispatcher === 'function') {
// save the raw dispatcher
app.httpclient[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?.httpclient?.[APP_HTTPCLIENT_AGENT]) {
app.httpclient.setDispatcher(app.httpclient[APP_HTTPCLIENT_AGENT]);
}
_mockAgent = null;
await agent.close();
},
};

0 comments on commit 3e7a504

Please sign in to comment.