mock-pool.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict'
  2. const { promisify } = require('node:util')
  3. const Pool = require('../dispatcher/pool')
  4. const { buildMockDispatch } = require('./mock-utils')
  5. const {
  6. kDispatches,
  7. kMockAgent,
  8. kClose,
  9. kOriginalClose,
  10. kOrigin,
  11. kOriginalDispatch,
  12. kConnected,
  13. kIgnoreTrailingSlash
  14. } = require('./mock-symbols')
  15. const { MockInterceptor } = require('./mock-interceptor')
  16. const Symbols = require('../core/symbols')
  17. const { InvalidArgumentError } = require('../core/errors')
  18. /**
  19. * MockPool provides an API that extends the Pool to influence the mockDispatches.
  20. */
  21. class MockPool extends Pool {
  22. constructor (origin, opts) {
  23. if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
  24. throw new InvalidArgumentError('Argument opts.agent must implement Agent')
  25. }
  26. super(origin, opts)
  27. this[kMockAgent] = opts.agent
  28. this[kOrigin] = origin
  29. this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false
  30. this[kDispatches] = []
  31. this[kConnected] = 1
  32. this[kOriginalDispatch] = this.dispatch
  33. this[kOriginalClose] = this.close.bind(this)
  34. this.dispatch = buildMockDispatch.call(this)
  35. this.close = this[kClose]
  36. }
  37. get [Symbols.kConnected] () {
  38. return this[kConnected]
  39. }
  40. /**
  41. * Sets up the base interceptor for mocking replies from undici.
  42. */
  43. intercept (opts) {
  44. return new MockInterceptor(
  45. opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts },
  46. this[kDispatches]
  47. )
  48. }
  49. cleanMocks () {
  50. this[kDispatches] = []
  51. }
  52. async [kClose] () {
  53. await promisify(this[kOriginalClose])()
  54. this[kConnected] = 0
  55. this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
  56. }
  57. }
  58. module.exports = MockPool