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!

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay