Skip to content

Commit 3046683

Browse files
Added request intercept handler
1 parent 2daca13 commit 3046683

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

cypress/support/commands/api_commands.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,15 @@ const getRequestIntercepted = () => Cypress.env('wasRequestIntercepted');
9090
* if the request was actually intercepted. This is useful for conditional API calls that may or may not happen like in tree navigations.
9191
* If false (default), the command will always wait for the intercepted request, where a request is always expected (e.g., button events).
9292
* @param {Function} options.triggerFn - Function that triggers the API call
93+
* @param {Function} [options.responseInterceptor] - Optional function that can modify the response before it's returned to the application.
94+
* This function receives the request object and can handle the response in different ways:
95+
* 1. req.reply({body: {...}}) - Immediately respond with a stubbed response (request never goes to origin)
96+
* 2. req.continue() - Let the request go to the origin server without modification
97+
* 3. req.continue((res) => { res.send({...}) }) - Let the request go to origin, then modify the response
98+
* Examples:
99+
* - Stub response: { responseInterceptor: (req) => req.reply({ body: { customData: 'value' } }) }
100+
* - Pass through to origin: { responseInterceptor: (req) => req.continue() }
101+
* - Modify origin response: { responseInterceptor: (req) => req.continue((res) => { res.send(200, { modified: true }) }) }
93102
* @param {Function} [options.onApiResponse] - Optional callback function that receives the interception object after the API call completes.
94103
* Use this to perform assertions on the response, extract data, or perform additional actions based on the API result.
95104
* Default is a no-op function. e.g. { onApiResponse: (interception) => { expect(interception.response.statusCode).to.equal(200); } }
@@ -105,6 +114,9 @@ Cypress.Commands.add(
105114
onApiResponse = () => {
106115
/* default implementation */
107116
},
117+
responseInterceptor = () => {
118+
/* default implementation */
119+
},
108120
}) => {
109121
/* ===== TODO: Remove this block once interceptApi command becomes stable ===== */
110122
const envVars = Cypress.env();
@@ -123,11 +135,12 @@ Cypress.Commands.add(
123135
}
124136
// Register the intercept if not already done
125137
if (!isAlreadyRegistered) {
126-
cy.intercept(method, urlPattern, () => {
138+
cy.intercept(method, urlPattern, (req) => {
127139
// Setting wasRequestIntercepted flag to true after request is intercepted
128140
if (waitOnlyIfRequestIntercepted) {
129141
setRequestIntercepted(true);
130142
}
143+
responseInterceptor(req);
131144
}).as(alias);
132145
cy.setInterceptedApiAlias(aliasObjectKey, alias);
133146
}

0 commit comments

Comments
 (0)