@@ -86,6 +86,9 @@ const getRequestIntercepted = () => Cypress.env('wasRequestIntercepted');
8686 * @param {string } options.alias - Unique alias for this interception
8787 * @param {string } options.method - HTTP method (default: 'POST')
8888 * @param {string|RegExp } options.urlPattern - URL pattern to intercept
89+ * @param {boolean } [options.waitOnlyIfRequestIntercepted=false] - When set to true, the command will only wait for the response
90+ * if the request was actually intercepted. This is useful for conditional API calls that may or may not happen like in tree navigations.
91+ * If false (default), the command will always wait for the intercepted request, where a request is always expected (e.g., button events).
8992 * @param {Function } options.triggerFn - Function that triggers the API call
9093 * @param {Function } [options.onApiResponse] - Optional callback function that receives the interception object after the API call completes.
9194 * Use this to perform assertions on the response, extract data, or perform additional actions based on the API result.
@@ -97,6 +100,7 @@ Cypress.Commands.add(
97100 alias,
98101 method = 'POST' ,
99102 urlPattern,
103+ waitOnlyIfRequestIntercepted = false ,
100104 triggerFn,
101105 onApiResponse = ( ) => {
102106 /* default implementation */
@@ -114,12 +118,16 @@ Cypress.Commands.add(
114118 // Check if this request is already registered
115119 const isAlreadyRegistered = ! ! interceptedAliasesMap [ aliasObjectKey ] ;
116120 // Setting wasRequestIntercepted flag to false initially
117- setRequestIntercepted ( false ) ;
121+ if ( waitOnlyIfRequestIntercepted ) {
122+ setRequestIntercepted ( false ) ;
123+ }
118124 // Register the intercept if not already done
119125 if ( ! isAlreadyRegistered ) {
120126 cy . intercept ( method , urlPattern , ( ) => {
121127 // Setting wasRequestIntercepted flag to true after request is intercepted
122- setRequestIntercepted ( true ) ;
128+ if ( waitOnlyIfRequestIntercepted ) {
129+ setRequestIntercepted ( true ) ;
130+ }
123131 } ) . as ( alias ) ;
124132 cy . setInterceptedApiAlias ( aliasObjectKey , alias ) ;
125133 }
@@ -129,8 +137,16 @@ Cypress.Commands.add(
129137
130138 // Wait for the intercepted request to complete
131139 cy . then ( ( ) => {
132- const isRequestIntercepted = getRequestIntercepted ( ) ;
133- if ( isRequestIntercepted ) {
140+ // If waitOnlyIfRequestIntercepted is true, check if the request was intercepted
141+ // and then wait for the response
142+ if ( waitOnlyIfRequestIntercepted ) {
143+ const isRequestIntercepted = getRequestIntercepted ( ) ;
144+ if ( isRequestIntercepted ) {
145+ cy . wait ( `@${ alias } ` ) . then ( onApiResponse ) ;
146+ }
147+ }
148+ // If waitOnlyIfRequestIntercepted is not required then directly wait for the response
149+ else {
134150 cy . wait ( `@${ alias } ` ) . then ( onApiResponse ) ;
135151 }
136152 } ) ;
0 commit comments