javascriptvue.jstestingcypresstailwind-css

How to write e2e tests with Cypress for a Vue Tailwind CSS app?


When I look at Cypress.io docs, there are examples of how to write tests and they use class selectors a lot. My problem is that my TailwindCSS app does not really have those kinds of classes but many small classes that would be very fragile to target for tests. What is a good solution to write e2e tests for a Tailwind app?

Example from the docs:

it('adds todos', () => {
  cy.visit('https://todo.app.com')

  cy.get('.new-input').type('write code{enter}').type('write tests{enter}')

  cy.get('li.todo').should('have.length', 2)

  cy.get('.action-email').type('fake@email.com').should('have.value', 'fake@email.com')
})

But my app looks nothing like it, I don't have class selectors like that:

<div class="relative flex min-h-screen flex-col justify-center overflow-hidden bg-gray-50 py-6 sm:py-12">
  <span class="absolute inset-0 bg-center"></span>

  <div class="relative bg-white px-6 pt-10 pb-8 shadow-xl ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg sm:px-10">
    <div class="mx-auto max-w-md">
      <img v-if="showLogo" src="logo.svg" class="h-6" />
      
      <div class="divide-y divide-gray-300/50">
        <div class="space-y-6 py-8 text-base leading-7 text-gray-600">
          My todo app
        </div>

        <button @click="createTodo" class="bg-white rouned-full px-2 py-4 border border-gray-200">
          Create a new todo
        </button>
      </div>
    </div>
  </div>
</div>

Wouldn't it be silly and fragile to try and target many classes like this? Is there a better alternative?

it('adds todos', () => {
  cy.visit('https://todo.app.com')

  cy.get('.bg-white.rouned-full.px-2.py-4.border.border-gray-200').first().click()
  cy.get('.space-y-6.py-8.text-base.leading-7.text-gray-600').should('have.value', 'fake todo')
})

Solution

  • Consider using data-cy attributes which is the recommendation from Cypress. It's pragmatic because you know exactly which elements are tagged, but could be labour-intensive.

    // Example - cypress.io
    
    <div class="container">
      <h1 class="Hero-TagLine mt-0" data-cy="tag-line" style="font-size:5.6rem;line-height:7rem">
        <div>The web has evolved.<br>Finally, testing has too.</div>
      </h1>
      <h2 class="Hero-ByLine mb-0" data-cy="by-line">Fast, easy and reliable testing...
    

    The recommendation from Testing Library is to use roles texts, and aria attributes.

    Also consider using traversal commands to navigate from key elements.