True is a library to provide unit testing for Sass. Today we are taking a brief look at how it works and how it can be incorporated into a project. While this won’t necessarily be something that you use on every project it is helpful if you are building a framework or set of standardized Sass files that you plan to re-use on other projects.
An Example of Usage
You can see basic usage of True to verify a function is behaving as expected. For purposed of our example I’m simply taking the
unpack function from Thoughtbot’s Bourbon. Scroll to the bottom of the SCSS to see the tests and click “View Compiled” button (available on hover) to view the test output.
Thoughts on organizing into a project
As you can see, this can make your generated CSS fairly messy and you need to import the
true library and actually look at your generated CSS to see what happens. While this is fine for exploring, we want something cleaner for a project.
With that in mind, True offers a few options which we can leverage.
This is a good way to handle tests and has a nice, clean output.
Command Line Test Runner
True also provides a CLI for running tests with ruby-sass – but it requires the ruby gem to be installed.
While it might work basic tests, this is not recommended for regular usage. Issues with it include:
- No output on success – you are left wondering if it even ran
- Very cluttered output on failure – you definitely know when it failed
- Requires ruby gem
I have created a sample project in GitHub (testing-sass-with-true) which you can clone to see a working example.
The Sass files that are responsible for building CSS for the site are all in the
scss/ directory as you would expect.
All test files are contained in the
test/ directory and they simply import the necessary Sass files from
scss/. This keeps our entire setup cleaner and keeps the test code from polluting the generated CSS.
I have used
npm for simplicity here, based on http://beletsky.net/2015/04/npm-for-everything.html. I will explore using Grunt or Gulp in a followup article.
To run the JS tests all you have to do is:
- setup npm via
- run the tests via
You can see the nice colored output from the test runner.
To see the CLI tests you need to first install the Ruby gem with
bundle install. Then you can see both passing and failing tests:
- passing tests with:
- failing tests with:
True is a nice library and provides good support for unit testing your Sass to be sure it is doing what you expect. Just be sure that you setup your project in such a way to support it.