Jump to the navigation menu

Testable Tailwind CSS plugins

A great thing about Tailwind CSS plugins being written in JavaScript is that they can be tested using tools like Jest.

Here's an example from https://github.com/opdavies/tailwindcss-plugin-jest-example (it may need updating to work with the latest Tailwind versions or to use the latest best practices):

function run(options = {}) {
  return postcss(
    tailwindcss({
      corePlugins: false,
      plugins: [plugin(options)]
    })
  )
  .process('@tailwind utilities;', {
    from: undefined
  })
}

expect.extend({
  toMatchCss: cssMatcher
})

test('it generates the correct classes with no variants', () => {
  const output = `
    .test {
      display: block
    }
  `

  run().then(result => {
    expect(result.css).toMatchCss(output)
  })
})

test('it generates the correct classes with variants', () => {
  const output = `
    .test {
      display: block
    }
    .hover\\:test:hover {
      display: block
    }
    .focus\\:test:focus {
      display: block
    }
  `

  run({ variants: ['hover', 'focus'] }).then(result => {
    expect(result.css).toMatchCss(output)
  })
});

Within the test, Tailwind can be run using PostCSS and generates styles based on a provided configuration, which is then checked against some expected output. If the generated styles match what was expected, the tests pass and the plugin is working as expected.

- Oliver

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an certified Drupal Triple Expert with 18 years of experience, a Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.