11cb0ef41Sopenharmony_ci'use strict' 21cb0ef41Sopenharmony_ci 31cb0ef41Sopenharmony_ciconst { promisify } = require('util') 41cb0ef41Sopenharmony_ciconst Client = require('../client') 51cb0ef41Sopenharmony_ciconst { buildMockDispatch } = require('./mock-utils') 61cb0ef41Sopenharmony_ciconst { 71cb0ef41Sopenharmony_ci kDispatches, 81cb0ef41Sopenharmony_ci kMockAgent, 91cb0ef41Sopenharmony_ci kClose, 101cb0ef41Sopenharmony_ci kOriginalClose, 111cb0ef41Sopenharmony_ci kOrigin, 121cb0ef41Sopenharmony_ci kOriginalDispatch, 131cb0ef41Sopenharmony_ci kConnected 141cb0ef41Sopenharmony_ci} = require('./mock-symbols') 151cb0ef41Sopenharmony_ciconst { MockInterceptor } = require('./mock-interceptor') 161cb0ef41Sopenharmony_ciconst Symbols = require('../core/symbols') 171cb0ef41Sopenharmony_ciconst { InvalidArgumentError } = require('../core/errors') 181cb0ef41Sopenharmony_ci 191cb0ef41Sopenharmony_ci/** 201cb0ef41Sopenharmony_ci * MockClient provides an API that extends the Client to influence the mockDispatches. 211cb0ef41Sopenharmony_ci */ 221cb0ef41Sopenharmony_ciclass MockClient extends Client { 231cb0ef41Sopenharmony_ci constructor (origin, opts) { 241cb0ef41Sopenharmony_ci super(origin, opts) 251cb0ef41Sopenharmony_ci 261cb0ef41Sopenharmony_ci if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { 271cb0ef41Sopenharmony_ci throw new InvalidArgumentError('Argument opts.agent must implement Agent') 281cb0ef41Sopenharmony_ci } 291cb0ef41Sopenharmony_ci 301cb0ef41Sopenharmony_ci this[kMockAgent] = opts.agent 311cb0ef41Sopenharmony_ci this[kOrigin] = origin 321cb0ef41Sopenharmony_ci this[kDispatches] = [] 331cb0ef41Sopenharmony_ci this[kConnected] = 1 341cb0ef41Sopenharmony_ci this[kOriginalDispatch] = this.dispatch 351cb0ef41Sopenharmony_ci this[kOriginalClose] = this.close.bind(this) 361cb0ef41Sopenharmony_ci 371cb0ef41Sopenharmony_ci this.dispatch = buildMockDispatch.call(this) 381cb0ef41Sopenharmony_ci this.close = this[kClose] 391cb0ef41Sopenharmony_ci } 401cb0ef41Sopenharmony_ci 411cb0ef41Sopenharmony_ci get [Symbols.kConnected] () { 421cb0ef41Sopenharmony_ci return this[kConnected] 431cb0ef41Sopenharmony_ci } 441cb0ef41Sopenharmony_ci 451cb0ef41Sopenharmony_ci /** 461cb0ef41Sopenharmony_ci * Sets up the base interceptor for mocking replies from undici. 471cb0ef41Sopenharmony_ci */ 481cb0ef41Sopenharmony_ci intercept (opts) { 491cb0ef41Sopenharmony_ci return new MockInterceptor(opts, this[kDispatches]) 501cb0ef41Sopenharmony_ci } 511cb0ef41Sopenharmony_ci 521cb0ef41Sopenharmony_ci async [kClose] () { 531cb0ef41Sopenharmony_ci await promisify(this[kOriginalClose])() 541cb0ef41Sopenharmony_ci this[kConnected] = 0 551cb0ef41Sopenharmony_ci this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) 561cb0ef41Sopenharmony_ci } 571cb0ef41Sopenharmony_ci} 581cb0ef41Sopenharmony_ci 591cb0ef41Sopenharmony_cimodule.exports = MockClient 60