|
| 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 | +); |
0 commit comments