Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
type RequestControls = {
  releaseRequest: () => void;
  rejectRequest: () => void;
};
 
/**
 * Network throttling utility for testing buffering scenarios
 */
export class Network {
  private static activeThrottles = new Map<string, () => void>();
  private static controlledDelays = new Map<string, RequestControls>();
 
  /**
   * Disable browser cache (equivalent to DevTools "Disable Cache" checkbox)
   */
  static disableBrowserCache(): void {
    cy.wrap(
      Cypress.automation("remote:debugger:protocol", {
        command: "Network.setCacheDisabled",
        params: {
          cacheDisabled: true,
        },
      }),
    );
  }
 
  /**
   * Enable browser cache back
   */
  static enableBrowserCache(): void {
    cy.wrap(
      Cypress.automation("remote:debugger:protocol", {
        command: "Network.setCacheDisabled",
        params: {
          cacheDisabled: false,
        },
      }),
    );
  }
 
  /**
   * Throttle network speed for specified URL pattern
   * @param urlPattern - URL pattern to throttle (can be glob pattern)
   * @param throttleKbps - Speed in Kbps (e.g., 50 for slow 3G)
   * @param alias - Unique alias for this throttle
   */
  static throttleNetwork(urlPattern: string, throttleKbps: number, alias: string): void {
    cy.intercept(
      {
        url: urlPattern,
        middleware: true,
      },
      (req) => {
        req.on("response", (res) => {
          res.setThrottle(throttleKbps);
        });
      },
    ).as(alias);
 
    // Store cleanup function
    Network.activeThrottles.set(alias, () => {
      // Cypress doesn't provide direct way to remove intercept,
      // so we'll override with a pass-through intercept
      cy.intercept(urlPattern, (req) => {
        req.reply();
      });
    });
  }
 
  /**
   * Add delay to network requests
   * @param urlPattern - URL pattern to delay
   * @param delayMs - Delay in milliseconds
   * @param alias - Unique alias for this delay
   */
  static delayNetwork(urlPattern: string, delayMs: number, alias: string): void {
    cy.intercept(
      {
        url: urlPattern,
        middleware: true,
      },
      (req) => {
        req.on("response", (res) => {
          // Wait for delay in milliseconds before sending the response to the client.
          res.setDelay(delayMs);
        });
      },
    ).as(alias);
 
    Network.activeThrottles.set(alias, () => {
      cy.intercept(urlPattern, (req) => {
        req.reply();
      });
    });
  }
 
  /**
   * Create controlled delay that can be manually released
   * @param urlPattern - URL pattern to delay
   * @param alias - Unique alias for this delay
   * @returns Object with releaseRequest and rejectRequest methods
   */
  static createControlledDelay(
    urlPattern: string,
    alias: string,
  ): {
    releaseRequest: () => void;
    rejectRequest: () => void;
  } {
    let resolveRequest: () => void;
    let rejectRequest: () => void;
 
    const requestPromise = new Promise<void>((resolve, reject) => {
      resolveRequest = resolve;
      rejectRequest = reject;
    });
 
    cy.intercept(
      {
        url: urlPattern,
        middleware: true,
      },
      (req) => {
        req.responseTimeout = 0; // Disable automatic timeout
        req.reply(async (res) => {
          try {
            await requestPromise;
            res.send();
          } catch (error) {
            res.send({ statusCode: 500, body: "Network error simulated" });
          }
        });
      },
    ).as(alias);
 
    const controls: RequestControls = {
      releaseRequest: () => cy.wait(0).then(() => resolveRequest()),
      rejectRequest: () => cy.wait(0).then(() => rejectRequest()),
    };
 
    Network.controlledDelays.set(alias, controls);
    Network.activeThrottles.set(alias, () => {
      if (Network.controlledDelays.has(alias)) {
        Network.controlledDelays.get(alias).releaseRequest();
      }
      Network.controlledDelays.delete(alias);
      cy.intercept(urlPattern, (req) => {
        req.reply();
      });
    });
 
    return controls;
  }
 
  /**
   * Combine throttling with additional delay
   * @param urlPattern - URL pattern to throttle
   * @param throttleKbps - Speed in Kbps
   * @param delayMs - Additional delay in milliseconds
   * @param alias - Unique alias for this throttle
   */
  static throttleWithDelay(urlPattern: string, throttleKbps: number, delayMs: number, alias: string): void {
    cy.intercept(
      {
        url: urlPattern,
        middleware: true,
      },
      (req) => {
        req.reply({
          throttleKbps: throttleKbps,
          delay: delayMs,
        });
      },
    ).as(alias);
 
    Network.activeThrottles.set(alias, () => {
      cy.intercept(urlPattern, (req) => {
        req.reply();
      });
    });
  }
 
  /**
   * Clear specific throttle by alias
   * @param alias - Alias of the throttle to clear
   */
  static clearThrottle(alias: string): void {
    const cleanup = Network.activeThrottles.get(alias);
    if (cleanup) {
      cleanup();
      Network.activeThrottles.delete(alias);
    }
 
    const controlledDelay = Network.controlledDelays.get(alias);
    if (controlledDelay) {
      controlledDelay.releaseRequest();
      Network.controlledDelays.delete(alias);
    }
  }
 
  /**
   * Clear all active throttles and delays
   */
  static clearAllThrottles(): void {
    Network.activeThrottles.forEach((cleanup, alias) => {
      cleanup();
    });
    Network.activeThrottles.clear();
 
    Network.controlledDelays.forEach((controls, alias) => {
      controls.releaseRequest();
    });
    Network.controlledDelays.clear();
  }
 
  /**
   * Get list of active throttles
   * @returns Array of active throttle aliases
   */
  static getActiveThrottles(): string[] {
    return Array.from(Network.activeThrottles.keys());
  }
 
  /**
   * Check if a specific throttle is active
   * @param alias - Alias to check
   * @returns True if throttle is active
   */
  static isThrottleActive(alias: string): boolean {
    return Network.activeThrottles.has(alias);
  }
}