cypressvuejs3tailwind-csscypress-component-test-runner

Running Cypress tests with TailwindCSS 3


I've been running my component tests via cypress open-ct for a while now, relying on importing /node_modules/tailwindcss/dist/tailwindcss.min.css.

Since upgrading to Tailwind v3 some of my tests are failing as there is no prebuilt CSS file I can import - everything is generated just in time.

For example, testing if a modal closes when clicking on a overlay that is fixed and full width fails as the whole modal is rendered so that it is inaccessible by Cypress.

Another side-issue that stems from not having access to Tailwind classes is that videos recorded when running tests in CI are unusable as they are just a bunch of random native elements.

I've been importing Tailwind like this at the top of each Test file (before describes)

import { mount } from '@cypress/vue'
import '/node_modules/tailwindcss/dist/tailwind.min.css'
import MultiSelectField from './MultiSelectField.vue'
import { ref } from "vue";

Any ideas how to include Tailwind (preferably globally) so tests won't fail?


Solution

  • You can use the Tailwind CLI to generate your stylesheet on the fly.

    Add this plugin in cypress/plugins/tailwind.js (be sure to change the -i source from ./src/styles/globals.css to your base CSS file):

    before(() => {
      cy.exec('npx tailwindcss -i ./src/styles/globals.css -m').then(
        ({ stdout }) => {
          if (!document.head.querySelector('#tailwind-style')) {
            const link = document.createElement('style')
            link.id = 'tailwind-style'
            link.innerHTML = stdout
    
            document.head.appendChild(link)
          }
        },
      )
    })
    

    Then, load the plugin by importing it in cypress/support/index.js:

    import '../plugins/tailwind'
    

    You should also set up a separate config file for your component tests, such as cypress/support/component.js, and specify that in your cypress.json config file:

    {
      "component": {
        "supportFile": "cypress/support/component.js",
      },
      "e2e": {
        "supportFile": "cypress/support/e2e.js"
      }
    }
    

    Then, only include import '../plugins/tailwind' in your cypress/support/component.js config file, so that you don't perform the JIT compilation for your E2E tests (since it's unnecessary).