Skip to content

Commit 033862c

Browse files
Add interceptApi command to prevent duplicate intercept aliases
1 parent ab2ae8c commit 033862c

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/* eslint-disable no-undef */
2+
3+
/**
4+
* Custom command to intercept API calls and wait for them to complete.
5+
* This command will:
6+
* 1. Register an intercept for the given alias and URL pattern if not already registered
7+
* 2. Execute the trigger function that makes the API call
8+
* 3. Wait for the intercepted request to complete if it was triggered
9+
*
10+
* @param {Object} options - The options for the intercept
11+
* @param {string} options.alias - Unique alias for this interception
12+
* @param {string} options.method - HTTP method (default: 'POST')
13+
* @param {string|RegExp} options.urlPattern - URL pattern to intercept
14+
* @param {Function} options.triggerFn - Function that triggers the API call
15+
*/
16+
Cypress.Commands.add(
17+
'interceptApi',
18+
({ alias, method = 'POST', urlPattern, triggerFn }) => {
19+
/* ===== TODO: Remove this block once interceptApi command becomes stable ===== */
20+
const envVars = Cypress.env();
21+
cy.log('Cypress Environment Variables:');
22+
cy.log(JSON.stringify(envVars, null, 2));
23+
/* ======================================================= */
24+
25+
// Check if this request is already registered
26+
const isAlreadyRegistered = !!Cypress.env('interceptedAliases')[alias];
27+
28+
// Register the intercept if not already done
29+
if (!isAlreadyRegistered) {
30+
cy.intercept(method, urlPattern).as(alias);
31+
32+
// Store the alias in the tracking object
33+
const interceptedAliases = Cypress.env('interceptedAliases');
34+
interceptedAliases[alias] = alias;
35+
Cypress.env('interceptedAliases', interceptedAliases);
36+
}
37+
38+
// Execute the function that triggers the API call
39+
triggerFn();
40+
41+
// Wait for the intercepted request to complete
42+
cy.wait(`@${alias}`);
43+
}
44+
);

cypress/support/e2e.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
// ***********************************************************
4141

4242
// Commands
43+
import './commands/api_commands.js';
4344
import './commands/custom_logging_commands.js';
4445
import './commands/element_selectors.js';
4546
import './commands/explorer.js';
@@ -76,4 +77,7 @@ beforeEach(() => {
7677
// Global hook run once before each test
7778
// cy.throttle_response(500, 56);
7879
// cy.stub_notifications();
80+
81+
// Reset the intercepted aliases tracking object
82+
Cypress.env('interceptedAliases', {});
7983
})

0 commit comments

Comments
 (0)