mock-client.js 1.5 KB

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