DEV Community

Cover image for How To Simplify API Request Handling with Page Object Models in Cypress
Martin Chudomel
Martin Chudomel

Posted on

How To Simplify API Request Handling with Page Object Models in Cypress

When writing Cypress tests, I often needed to use cy.intercept() and cy.wait() to monitor and assert specific API requests. However, I found myself repeatedly defining the same request interception in multiple tests. This repetition became a maintenance headache when the API URL changed, forcing me to update numerous test files.

To solve this, I applied the Page Object Model (POM) pattern, centralizing request interceptions and waits. This allowed me to manage API requests in one place, simplifying test maintenance and reducing code duplication.

The Problem: Repeated Interceptions

Here’s how my tests looked before adopting the POM approach:

it('Check trackings', () => {
    cy.intercept('GET', trackerUrl).as('tracker')
    cy.visit('/')
    cy.wait('@tracker').then((interception) => {
        expect(interception.request.body.registration.hashed_email).to.eq(hashed_email)
        expect(interception.request.body.registration.urid).not.to.be.undefined
    })
})
Enter fullscreen mode Exit fullscreen mode

While this worked, the same request interception was duplicated across many tests.

The Solution: Centralizing in a Page Object Model

I moved the interception and wait logic into a POM class. Here’s how the updated test looks:

// don´t forget to import your page object model first
it('Check trackings', () => {
    homePage.interceptTracker()
    cy.visit('/')
    homePage.waitTracker().then((interception) => {
        expect(interception.request.body.registration.hashed_email).to.eq(hashed_email)
        expect(interception.request.body.registration.urid).not.to.be.undefined
    })
})
Enter fullscreen mode Exit fullscreen mode

In the homePage object:

class HomePage {
    const trackerUrl = '...'

    // other functions

    interceptTracker() {
        return cy.intercept('GET', trackerUrl).as('tracker')
    }

    waitTracker() {
        return cy.wait('@tracker')
    }
}

const homePage = new HomePage()
Enter fullscreen mode Exit fullscreen mode

When to Use Custom Commands

If the same interception logic applies to multiple pages or components, defining Cypress custom commands could be a better approach. This keeps your POMs cleaner while ensuring request handling is still centralized.

Key Takeaway

The Page Object Model isn’t just for managing UI elements. By applying it to request interceptions, I simplified API monitoring in Cypress tests and reduced maintenance effort. If you’re struggling with repetitive Cypress test logic, consider extending your POMs beyond UI elements!

Top comments (0)