Sass Unit Testing

02 Apr 2014

We all know that testing is good, and most of us hopefully already write tests for our front-end JavaScript code – but is it needed for our Sass code as well?

We need to think about long-term maintenance as our Sass projects and libraries gets more and more powerful. Just look at some of the things Sass can do today, things nobody would’ve imagined just a few years ago:

The term Sass unit testing is not referring to visual regression testing of the visual end-result, but instead logical unit tests focused on the core functions of a library. The term is also not referring to linting of sassor scss, if that’s what you’re looking for scss-lint may be for you.

Continuous integration

If you’re using continuous integration in your deployment process you are probably already running existing tests before deploying, the first step to making sure your Sass doesn’t break on deployment is making sure that it can compile with errors.

In case you’re already using Grunt for your local development workflow it would make sense to just make Grunt run your test and build tasks. If you’re using Travis it’s just a few simple steps to make your Grunt tasks run on every new build.

No matter what build system you are using, the key is that the build will fail if compilation of Sass/Compass fails - the last thing we want is for broken output css to make it into production.

Bootcamp

A BDD-style framework that doesn’t rely on any frameworks.

Bootcamp is developed by James Kyle who have done some crazy things with Sass, checkout his GitHub. The syntax for Bootcamp is clean and obvious, especially if you’ve worked with BDD frameworks in other languages before. You begin a new test suite by calling the mixin describe with the title for the spec suite and then the @content block inside:

@includedescribe("A suite"){@includeit("contains spec with an expectation"){@includeshould(expect(true),to(be(true)));}}

Specs are called by the mixin it which just like describe takes the name/title and a @content block. The spec contains at least one expectation which evaluates to either true or false, a spec with at least one false assertion is a failing spec.

The syntax for defining suites and specs are important, but the matchers that are available in assertions are just as important. Bootcamp comes with a bunch of rich matchers already included. An extensive list and demo of each matcher is right here.

It’s possible to disable suites and specs by changing the mixins to xdescribe and xit, just like Jasmine.

Going forward

We as a community need to figure out what it is that we want to test. What is missing in the current frameworks and maybe even in the Sass language. How are we going to do unit testing in Sass in the future.

Do we want a standard set of assertions and matchers in the Sass language, which we as a community can build different language/syntaxes on top of?