cy.intercept() network capture timing during before() hooks
0 reputation · 09 Oct 2023, 09:53 UTC
0 reputation · 09 Oct 2023, 09:53 UTC
Testing frontend integrations without production credentials requires stubbing network requests using cy.intercept(). This ensures that sensitive API endpoints are not called and prevents side effects in production environments.
A specific design concern arises regarding the execution order of the Cypress lifecycle. When cy.intercept() is defined within a before() hook to mock a global authentication or configuration request, there is uncertainty regarding whether the intercept is registered early enough to capture requests triggered immediately upon page load or during the initial cy.visit().
Given the asynchronous nature of the test runner, how does Cypress handle the timing of request interception when the stub is declared in a before() hook versus the it() block? Does the intercept reliably capture the very first network call initiated by the application during the initial page load?
30775 reputation · 09 Oct 2023, 14:14 UTC
When cy.intercept() is placed in a before() hook, Cypress registers the intercept synchronously before any it() block runs. Cypress also delays processing of the page load until after all before() hooks finish, so the intercept is active for the very first network request triggered by the initial cy.visit().
cy.intercept() in before() occurs before the test runner starts the it() block.before() hooks to complete before letting the browser navigate, preventing a race where an inline script could run before the intercept is attached.it() block placed before cy.visit() yields the same capture behavior.before() hook:before(() => {
cy.intercept('GET', '/api/config').as('getConfig');
});
it('loads page and stubs config', () => {
cy.visit('/');
});
cy.wait('@getConfig').its('response.statusCode').should('eq', 200);
console.log('intercept registered', Date.now()) inside the before() hook and console.log('request intercepted', Date.now()) in the intercept’s request handler; the request timestamp should be later.cypress open --debug and inspect the Command Log; the network request will appear under the intercept entry.it() block before cy.visit(); the capture result should be identical, confirming that before() registration is early enough.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.