Skip to content

Commit 3a3205c

Browse files
Wait only when request is triggered, controlled via an env flag
1 parent 88ab513 commit 3a3205c

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

cypress/support/commands/api_commands.js

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,28 @@ Cypress.Commands.add('resetInterceptedApiAliases', () =>
5353
Cypress.env('interceptedAliases', {})
5454
);
5555

56+
/**
57+
* Sets the request interception flag in Cypress environment.
58+
* This flag is used to track whether a request matching an intercept pattern was detected.
59+
*
60+
* @param {boolean} value - The value to set for the flag (true if request was intercepted, false otherwise)
61+
* @example
62+
* // Mark a request as intercepted
63+
* setRequestIntercepted(true);
64+
*
65+
* // Reset the interception flag
66+
* setRequestIntercepted(false);
67+
*/
68+
const setRequestIntercepted = (value) =>
69+
Cypress.env('wasRequestIntercepted', value);
70+
71+
/**
72+
* Gets the current value of the request interception flag from Cypress environment.
73+
* This flag indicates whether a request matching an intercept pattern was detected.
74+
* @returns {boolean} The current value of the request interception flag
75+
*/
76+
const getRequestIntercepted = () => Cypress.env('wasRequestIntercepted');
77+
5678
/**
5779
* Custom command to intercept API calls and wait for them to complete.
5880
* This command will:
@@ -91,19 +113,26 @@ Cypress.Commands.add(
91113
const aliasObjectKey = `${method.toLowerCase()}-${alias}`;
92114
// Check if this request is already registered
93115
const isAlreadyRegistered = !!interceptedAliasesMap[aliasObjectKey];
94-
116+
// Setting wasRequestIntercepted flag to false initially
117+
setRequestIntercepted(false);
95118
// Register the intercept if not already done
96119
if (!isAlreadyRegistered) {
97-
cy.intercept(method, urlPattern).as(alias);
120+
cy.intercept(method, urlPattern, () => {
121+
// Setting wasRequestIntercepted flag to true after request is intercepted
122+
setRequestIntercepted(true);
123+
}).as(alias);
98124
cy.setInterceptedApiAlias(aliasObjectKey, alias);
99125
}
100126

101127
// Execute the function that triggers the API call
102128
triggerFn();
103129

104130
// Wait for the intercepted request to complete
105-
cy.wait(`@${alias}`).then((interception) => {
106-
onApiResponse(interception);
131+
cy.then(() => {
132+
const isRequestIntercepted = getRequestIntercepted();
133+
if (isRequestIntercepted) {
134+
cy.wait(`@${alias}`).then(onApiResponse);
135+
}
107136
});
108137
});
109138
}

0 commit comments

Comments
 (0)