Search code examples
testingnext.jscypresstdd

Cypress: get nested components using id in Next Js


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'. This is the screenshot of webage


Solution

  • Why not use the id.

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

    You can directly use the text to identify and click the element as well.

    cy.contains('Submit Damage Report').click()
    cy.contains('View Damage Reports').click()