Repository navigation
Replies: 3 comments
|
The |
This comment was marked as spam.
This comment was marked as spam.
|
If your wrapper passes the TLS agent explicitly as A practical pattern is to inject the dispatcher when constructing your API wrapper. Production passes your existing TLS-configured Agent; tests pass a MockAgent. There is no need to merge the two agents for fully mocked requests. // api.mjs
import { request } from 'undici'
export function createApi(dispatcher) {
return {
async getJson(url) {
const { statusCode, body } = await request(url, {
method: 'GET',
dispatcher,
})
if (statusCode < 200 || statusCode >= 300) {
await body.dump()
throw new Error('HTTP ' + statusCode)
}
return body.json()
},
}
}
// Production setup, where your TLS agent is already configured:
// const api = createApi(tlsAgent)Then an illustrative test is: import { test } from 'node:test'
import assert from 'node:assert/strict'
import { MockAgent } from 'undici'
import { createApi } from './api.mjs'
test('uses the injected dispatcher', async () => {
const mock = new MockAgent()
mock.disableNetConnect()
try {
mock.get('https://service.test')
.intercept({ path: '/status', method: 'GET' })
.reply(200, { ok: true }, {
headers: { 'content-type': 'application/json' },
})
const api = createApi(mock)
assert.deepEqual(await api.getJson('https://service.test/status'), {
ok: true,
})
mock.assertNoPendingInterceptors()
} finally {
await mock.close()
}
})Disabling network access makes a missed interception fail rather than silently contact the service. The caller owns the injected agent's lifecycle: close the production agent at shutdown and the test agent during cleanup. If your code calls a separately constructed References: dispatcher selection in the source, MockAgent documentation. I reviewed these APIs, but have not run the sample against your setup. |
Uh oh!
There was an error while loading. Please reload this page.
I use an agent to enable TLS options. I want to begin using the mock agent in tests, but that gets overridden by the TLS agent. What is a practical pattern for having the tls agent defined locally, with the ability to override the returned value vai a mock?
All reactions