Cypress - intercept() Method

Last Updated : 24 Oct, 2024

The intercept() method in Cypress is used to intercept and mock network requests, and responses, or modify them on the fly. It is an essential tool for testing web applications by simulating different server responses, such as success, failure, or timeouts, without needing to modify the actual backend.

Syntax:

cy.intercept(method, url, response)

Usage of intercept() Method

The intercept() method can be used to:

  • Mock or stub network requests (like GETPOSTPUT, etc.).
  • Simulate different responses from the server, including status codes and data.
  • Spy on network requests and assert that they were made correctly.

Arguments:

  • method (Optional): The HTTP method to intercept (GETPOSTPUTDELETE, etc.). If omitted, all methods are intercepted.
  • url (Required): The URL or route that the request should match (can be a string or a regex).
  • response (Optional): The stubbed response to send back. Can be a fixture, an object, or a function that returns a response.

Examples

Example 1: Mocking a GET Request

In this example, we’ll intercept a GET request to an API and mock the response with custom data.

HTML File (index.html):
Save this file in the root directory of our local server (e.g., localhost:3000).

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mock API Example</title>
</head>
<body>
    <h1>API Data:</h1>
    <div id="apiData"></div>

    <script>
        fetch('https://api.example.com/data')
            .then(response => response.json())
            .then(data => {
                document.getElementById('apiData').innerText = JSON.stringify(data);
            });
    </script>
</body>
</html>


Cypress Test File (intercept_get_spec.js):
Save this file in the cypress/e2e folder (for Cypress v10 and above) or cypress/integration folder (for older versions).

JavaScript
describe('Mocking a GET request with `intercept()`', () => {

  beforeEach(() => {
    // Visit the HTML file hosted on localhost
    cy.visit('http://localhost:3000');
  });

  it('should intercept the GET request and return mocked data', () => {
    // Intercept the GET request and mock the response
    cy.intercept('GET', 'https://api.example.com/data', {
      statusCode: 200,
      body: {
        message: 'Mocked Data',
        items: ['Item 1', 'Item 2', 'Item 3']
      }
    }).as('getData');

    // Wait for the intercepted request to complete
    cy.wait('@getData');

    // Assert that the mocked data is displayed in the DOM
    cy.get('#apiData').should('contain.text', 'Mocked Data');
  });

});


Explanation of the Test:

  • HTML Structure: The HTML file contains a simple fetch() request that retrieves data from an API and displays it in a div element.
  • Cypress Test: The intercept() method is used to intercept the GET request to https://api.example.com/data and return a mocked response with custom data. The test verifies that the mocked data is displayed correctly on the page.

Output:

intercept11
Output


The test will visit the page, intercept a GET request to an API and mock the response with custom data.

Example 2: Mocking a POST Request

In this example, we’ll intercept a POST request and mock the response to simulate form submission behavior.

HTML File (index.html):
Save this file in the root directory of our local server (e.g., localhost:3000).

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mock POST Example</title>
</head>
<body>
    <form id="contactForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <button type="submit">Submit</button>
    </form>
    <div id="responseMessage"></div>

    <script>
        document.getElementById('contactForm').addEventListener('submit', function(event) {
            event.preventDefault();

            const formData = {
                name: document.getElementById('name').value
            };

            fetch('https://api.example.com/submit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('responseMessage').innerText = data.message;
            });
        });
    </script>
</body>
</html>


Cypress Test File (intercept_post_spec.js):
Save this file in the cypress/e2e folder (for Cypress v10 and above) or cypress/integration folder (for older versions).

JavaScript
describe('Mocking a POST request with `intercept()`', () => {

  beforeEach(() => {
    // Visit the HTML file hosted on localhost
    cy.visit('http://localhost:3000');
  });

  it('should intercept the POST request and return a mocked response', () => {
    // Intercept the POST request and mock the response
    cy.intercept('POST', 'https://api.example.com/submit', {
      statusCode: 201,
      body: { message: 'Form submitted successfully!' }
    }).as('postForm');

    // Fill the form and submit
    cy.get('#name').type('John Doe');
    cy.get('form').submit();

    // Wait for the intercepted request
    cy.wait('@postForm');

    // Assert the mocked response is displayed in the DOM
    cy.get('#responseMessage').should('have.text', 'Form submitted successfully!');
  });

});


Explanation of the Test:

  • HTML Structure: The HTML file contains a simple form that triggers a POST request to submit data. Upon submission, the response message is displayed on the page.
  • Cypress Test: The intercept() method is used to intercept the POST request and return a mocked response. The test verifies that the correct response message is displayed after form submission.

Output:

interceptt
Output


The test will visit the page,intercept a POST request and mock the response to simulate form submission behavior.

Running the Test

  1. Start the Local Server: Ensure that the local server is running and serving the index.html file at http://localhost:3000.
  2. Open Cypress Test Runner: Run the following command in our terminal:
    npx cypress open
  3. Run the Test: Click on intercept_get_spec.js or intercept_post_spec.js in the Cypress Test Runner to execute the test and view the results.

Conclusion

The intercept() method is a powerful tool in Cypress for mocking network requests and responses. It allows us to test the application’s behavior under various scenarios without relying on the actual backend, making our tests more stable and faster. By using intercept(), we can simulate server responses, mock data, and verify how our application handles different situations

Comment

Explore