0
0
Cypresstesting~15 mins

Slot testing in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify slot content rendering and interaction
Preconditions (2)
Step 1: Open the web page containing the slot component
Step 2: Verify that the default slot content is visible
Step 3: Verify that the named slot content is visible in the correct slot
Step 4: Click a button inside the slot content that triggers an event
Step 5: Verify that the event handler is called and the expected change happens
✅ Expected Result: The slot contents render correctly in their slots, and clicking the button inside the slot triggers the expected event and UI change
Automation Requirements - Cypress
Assertions Needed:
Check visibility of default slot content
Check visibility of named slot content
Check that clicking button inside slot triggers expected UI change
Best Practices:
Use cy.get() with data-testid attributes for selectors
Use Cypress commands for interaction and assertions
Avoid hardcoded waits; use built-in Cypress retries
Keep tests isolated and independent
Automated Solution
Cypress
describe('Slot Component Testing', () => {
  beforeEach(() => {
    cy.visit('/slot-component-page')
  })

  it('should display default slot content', () => {
    cy.get('[data-testid="default-slot"]').should('be.visible').and('contain.text', 'Default Slot Content')
  })

  it('should display named slot content', () => {
    cy.get('[data-testid="named-slot"]').should('be.visible').and('contain.text', 'Named Slot Content')
  })

  it('should trigger event and update UI when button inside slot is clicked', () => {
    cy.get('[data-testid="slot-button"]').click()
    cy.get('[data-testid="event-result"]').should('be.visible').and('contain.text', 'Event Triggered')
  })
})

This Cypress test suite checks the slot component on the page.

beforeEach loads the page before each test.

The first test verifies the default slot content is visible and contains expected text using cy.get with a data-testid selector for reliability.

The second test checks the named slot content similarly.

The third test clicks a button inside the slot and verifies that an event triggers a UI update by checking the presence and text of an element that shows the event result.

Using data-testid attributes helps keep selectors stable and clear. Cypress commands handle waiting and retries automatically, so no manual waits are needed.

Common Mistakes - 3 Pitfalls
Using CSS classes or element tags as selectors instead of data-testid
Using cy.wait() with fixed time instead of relying on Cypress automatic waits
Not isolating tests and relying on state from previous tests
Bonus Challenge

Now add data-driven testing with 3 different slot content scenarios

Show Hint