Home > OS >  Cypress: get nested components using id in Next Js
Cypress: get nested components using id in Next Js

Time:08-09

I am going to write tests in cypress. The component which I going to test is below mentioned.

import Layout from "../../components/layout"
import ActionAreaCard from '../../components/card'
import Grid from '@mui/material/Grid';

export default function HomePage() {
    return (
        <Layout id='layout'>
            <Grid container spacing={2}>
                <Grid item xs={6}>
                    <ActionAreaCard
                       id='action-card-submit'
                       title='Submit Damage Report'
                       href="/view/data-submission"
                       imagePath='/assets/images/car-damage.jpg'
                     />
                </Grid>
                <Grid item xs={6}>
                    <ActionAreaCard
                       id='action-card-view'
                       title='View Damage Reports'
                       href="/view/view-reports"
                       imagePath='/assets/images/damage-report.jpg' />
                </Grid>
            </Grid>
        </Layout>
    )
}

I need to test navigation after clicking 'ActionAreaCard'. I have done it so far as follows.

it('should navigate to the data submissions page', () => {
    // Start from the index page
    cy.visit('http://localhost:3000/')

    // Find a button with an href attribute containing "/view/data-submission" and click it
    cy.get('a[href*="/view/data-submission"]').click()
  })

But I need to find the component by 'id'.

CodePudding user response:

Why not use the id.

cy.get('#action-card-submit').click()

CodePudding user response:

You have a couple of options when searching by id

  • use the attribute syntax cy.get('id=["action-card-submit"]')
  • use shorthand cy.get('#action-card-submit'), but this can fail if special characters are in the id
  • Related