Should you unit test CSS?

When I told a college I was going to write some unit tests for CSS they went crazy, and I do see why, however I think it can be valuable in the right way. I would like to describe to you why I think doing unit tests on CSS can be worth your time as a developer and also beneficial to the project.

Why oh why you may ask would you unit test CSS? Styles change so often, the style might be abstract from the code and they can be hard to test. You can’t test just the code, you have to test it for what it is, which is User Interface(UI) coding. Therefore you need to test it through the UI with something like Selenium, that boots up a browser and checks the UI. Though even if you use this technology then testing literally the size of the font and the colour of the background, which have no variable changes, you not testing properly.

Normally when you are unit testing, it is on something that can change depending on multiple variables, so testing the font size isn’t that. When you are testing them things they can only change if you want them to, so you not testing the code, you’re testing that you remembered to update the test. For example, if you have a ‘h1′ with a font size ’14px’ and write a unit test to check the browser has rendered a ‘h1’ with that size, then you have a change come in. You change the font size and now your unit test fails, so you update the test case, but what have you just shown to the project? You have proved that the font has been updated in both places.

It also gets hard when you are testing with browsers, as each browser will interpret the CSS in different ways. They render different, so when you test ‘1em’ is ’14px’ you might get a different answer in another browser.

Therefore why do I think you should unit test CSS?

Well that’s more because I am not saying to test the CSS purely, but to test modular items. In the project I work on there are modules in the site that share classes. Things like a promotion box with a background colour and a banner with the same background colour. We use the CSS pre-processor called LESS, so the background colour is stored in a variable shared across the code base. If a developer decides to change that variable for the banner, we want the unit test to flag that changing this colour effects the promotion box as well.

Example CSS:

@bg-color: #66bb6a;

.banner { background-color:@bg-color;}
.promo { background-color:@bg-color;}

This is why we should unit test, because we want to know if a classes style changes then what else does it effect. Imagine the above CSS lines were in separate files. You change the ‘@bg-color’ as you want the banner to be a different colour and then the unit test flags that the promotion box is incorrect. The value from this means the developer can find out what breaking changes they have introduced, which helps them decide it should all change or no I need a new class.

There is also testing where it takes graphical images and compares the two, but this is browser and code structure dependent. You can to make sure you can test the code in all situations and that’s why a banner for example is better than a whole page.

In our organisational structure then CSS is in a separate code base as the HTML it is running on, due to the CSS project being used in multiple projects. Therefore, we can’t test against the project’s code base, instead we need to create a running example each time. This has it benefits as we then have a working example to demo to the HTML developers.

This is where and why I think there is value in doing unit testing on CSS, but what do you think? Do you do it already or do you think it is a waste of time?

Guide to the Style Guide

Let first start with what this post is not and that is a style guide for clothing, make up or hair. This is about Coding Style Guides, what they are, if you should have one and if so then what one. I will mainly be following it through with JavaScript, but the knowledge can be transferred to other languages as it is the principle that I am looking at.

What is a style guide?

A Style Guide is a set of rules for your code to follow. These rules start from as simple as putting a semicolon at the end of the lines, and only using single quotes around strings. However the rules can be expanded to describe how you should format your code, for example how to format a function, the file naming convention and how to set up error checking. In short it is a guide of rules and patterns for developers to follow to create a consistent and fluent code.

Style Guides and their practice have been about for many years, but I feel with more languages and standards being put in place they have become more prominent. One of the earliest writing is a book called The Elements of Programming Style, which talks about the coding rules from its time for Fortran and PL/I languages. Though the languages are more out of date, the principles are not and can still be taken into account for todays standards. Most tutorials and beginners guide to languages, will also have some kind of style guide in them, so you can learn from their patterns what to conform to.

These guides don’t have to just be words on a page as well. The guides are able to be built into your Continuous Integration Builds. This would mean when your application builds it can produce errors or warning about your code and how to fix them before you merge into the shared code base.  Better yet,  you can get extensions built into most all the common coding editors that will evaluate your code as you type or on save of the code. Therefore you don’t need to wait until the end point when you are checking in to find out your problems. This can save time and also drill in the practices to your mind, so soon you will be throwing out the styles as you go with no help.

Should you have one?

This is a simple question with a simple answer, yes. Why would you not have one of these in practice at your company or even in your personal workflow. To conform to a style guide is an easy task for anyone to get started as there are so many tools to test your code. However if you have a large code base and then you decide to get a guide in place then it could take sometime, but worth it. Think if you have all types of developers putting their own twist in the code base and then they need to read each other code. It would create a bit of a muddle as they would need to understand the previous developer patterns to understand the code. Worst thing would be, does that developer conform to the previous developer standard or put their own in. This would then create a hybrid that creates more hassle for the next developer.

As you can see the guides can benefit you a lot, but not just for other developers reading your code. When you are creating code you want to make sure it is readable by yourself as well. If you think about, that you might not come back to a peace of code for a long time, with a style guide in place and in practice, you would be able to read the code more easily. It also then gives you a standard of coding, so your not just spitting out some Frankenstein code that just about works, but instead you always have a consistent level of code produced. With consistence code and naming conventions it then also make life easier when your 30,000 lines down the bottom of the page and you need to remember how you call that method. The style guide that pushes you to have a pattern to your naming, will then give you the ability to know how the method will be named. Therefore you won’t need to hunt it down as you will either just know the name or at minimal know how to search for it.

The people it should also be benefitting is the other developers working on the same code and also the company that could be recruiting another developer. If the standard is in place then it doesn’t matter who walks up to your code, they will be able to read it easy and also be able to update the code easier. The other perks of following the guide are the same that will benefit the individual user like simpler to find files names, update code and keep consistency.

Which one?

Well 99% of the time I would say not to build your own, but there is that small 1% I would say yes. This 1% time I would say yes, is for if you are a big enough company to require your own style guide. As the guide is just for coding then there is not customer vision of this, therefore it is not vital that the style guide represents your company image. Saying that though, some companies may prefer to have there own rules to follow as it might fall inline with other style guide or other company procedures. Either way it should only really be done if they must have to.

The reason to still use a popular  open source one is because it is just that, open source. This would mean that when the ECMAScript gets updated or any other language versioned, the community will update the style guide to comply with the latest version. This can take some time if it is your own, to update to a new version and have meetings internally to decide what the update is. However if the open source owner or community do it, then you don’t have to.

This then also back up the point that if another developer is recruited, they may know the open source style guide and be able to pick up the code base easier. If the style guide managed by your company or yourself, then you have no chance of the developer understanding the guide first time.

If you do decide to be in the 99% section, then which guide do you go for? This is where the power of the internet comes in. As I mentioned at the beginning, I am focusing this on JavaScript, but it can be transferred to other languages. Therefore for the JavaScript world I would suggest Airbnb Style Guide, because from what I have read and researched it is the most used guide. Of course this doesn’t make it the right guide, but other than the majority of the developer community can’t be wrong, the guide also looks good. From me using it I can tell it is up to date, well maintained and well supported by other extensions like linters. This for me says it is a good choice to go for and so I would use the same method for looking at other style guides for other languages.

To find other guide I would suggest using a search engine to find a guide for your chosen language, or speaking of search engine, Google has a style guide for a lot of languages and it will of course be up to date. You can find it here on Git Hub.

Some Further Reading…


How to put items in a Circle in CSS LESS

Through the depths of the internet I have search and found a method to put items on a circle using a CSS preprocessor. However it was in SCSS and I work in LESS, by which I mean the preprocessor not just less things. So I have converted it over to the dark side of LESS and broken down how it works below, I hope this helps.

Let’s start off with the SCSS version of items on a circle by Hugo Giraudel from his site.

/// Mixin to put items on a circle
/// [1] - Allows children to be absolutely positioned
/// [2] - Allows the mixin to be used on a list
/// [3] - In case box-sizing: border-box has been enabled
/// [4] - Allows any type of direct children to be targeted
///
/// @param {Integer} $nb-items - Number or items
/// @param {Length} $circle-size - Container size
/// @param {Length} $item-size - Item size
/// @param {String | false} $class-for-IE - Base class name for old IE
@mixin distribute-on-circle(
$nb-items,
$circle-size,
$item-size,
$class-for-IE: false
) {

$half-item: ($item-size / 2);
$half-parent: ($circle-size / 2);

position: relative; /* 1 */
width: $circle-size;
height: $circle-size;
padding: 0;
border-radius: 50%;
list-style: none; /* 2 */
box-sizing: content-box; /* 3 */

> * { /* 4 */

display: block;
position: absolute;
top: 50%;
left: 50%;
width: $item-size;
height: $item-size;
margin: -$half-item;

}

$angle: (360 / $nb-items);
$rot: 0;

@for $i from 1 through $nb-items {

@if not $class-for-IE {
> :nth-of-type(#{$i}) {
transform: rotate($rot * 1deg) translate($half-parent) rotate($rot * -1deg);
}
} @else {
> .#{$class-for-IE}#{$i} {
// If CSS transforms are not supported
$mt: sin($rot * pi() / 180) * $half-parent - $half-item;
$ml: cos($rot * pi() / 180) * $half-parent - $half-item;
margin: $mt 0 0 $ml;
}

}

$rot: ($rot + $angle);
}

}

So now you have seen the SCSS, let’s go to the LESS CSS.

First lets build the method you will be calling in the CSS, which like most of this we will just be copying the SCSS. Instead of putting an action call before the method name like in SCSS (@mixin), we call it like a class in standard CSS. In LESS we also identify variables with ‘@’ instead of the ‘$’. This means the above method of calling a method turns into the below.

.on-circle(@item-count, @circle-size, @item-size) {

}

There are then some manadatory styles that we need for the container to work. At this point though you could also add in some of your own custom style for the container as well. When we call the method we will be putting it in the containers class. We also use the variable ‘circle-size’ for the width and height. For this I used the Unit function for LESS, so it could be swapped out to be in percentage, em, rem or anything else. Rembering to use the ‘@’ to call the variable and not the ‘$’.

.on-circle(@item-count, @circle-size, @item-size) {

position: relative;
width: unit(@circle-size, px);
height: unit(@circle-size, px);
padding: 0;
margin:auto;
border-radius: 50%;

}

Within the method we now call upon the children, but to make sure we only affect the children of the container and nothing further down we got the direct child symbol added in (‘>’). Also because you could be using div’s, span’s or li elements as the children, it using the any type of element selector (‘*’).

A method to centre items up, which we have used here, is to set the width and height 50%, then move the item back half of its size. We get the children’s item size sent in the method to use for this, plus we got the Unit function used in case your making this responsive.

> * {

display: block;
position: absolute;
top: 50%;
left: 50%;
width: unit(@item-size, px);
height: unit(@item-size, px);
margin: unit(-(@item-size / 2), px);

}

Next is the loop for each child and it gets a bit different here for the conversion so ill break it down a bit more. The loop in SCSS looks more like a general loop you would see in JavaScript or some other languages, but the way to do in LESS is to call it like a method with an exception on the side. You can see from the example below I have called the method ‘cl’ for ‘children loop’, passed in two variables and then put a when clause on the side. This will then run while ‘i’ is greater than zero.

.cl(@i,@r) when (@i > 0) {

}

However this will be an infinite loop at the moment as ‘i’ never changes and if we just change ‘i’ in the loop then the ‘when’ clause won’t know about it. What we can do is call the loop method again inside, but of course minus 1.

Our ‘i’ variable is going to be our item count as we want to loop through each of the items. The second variable is our rotation for the item we are at, so for this reason we need to calculate out how much rotation we need for each item. This will be 360 degree’s divided between how many items we have, which will give us the 1% rotation value for each item on the circle.

You can then see we call the method at the bottom after we create the method, or the LESS won’t know what you are calling. Then in each iteration we iterate the variables by removing 1 from the item count and adding another degree percentage to the previous degree.

@angle: (360 / @item-count);

.cl(@i,@r) when (@i > 0) {

@rot: @r + @angle;
.cl(@i - 1,@rot);

}

.cl(@item-count,0);

We can now convert in the style for each of the children items, which is added in the loop. The simple conversion differences are the variables in the nth-of-type and the degrees. Instead of the ‘$’ symbol we use the ‘@’.  Then compared to the SCSS version, I did the calculation within the translate instead of using a variable. I halfed the circle and again to make it flexible to change I used the Unit function.

&:nth-of-type(@{i}) {

transform: rotate(@r * 1deg)  translate(unit(@circle-size/2,px)) rotate(@r * -1deg);

}

All Together Now

At the end of the road with all the pieces we have the final product. You can then use the following as the base to build your items in a circle. I have done a small demo on my Code Pen here.

/// Mixin to place items on a circle
/// @author Hugo Giraudel
/// @author Ana Tudor
/// @author convert SASS to LESS Christopher Pateman

.on-circle(@item-count, @circle-size, @item-size) {

position: relative;
width: unit(@circle-size, px);
height: unit(@circle-size, px);
padding: 0;
margin:auto;
border-radius: 50%;

> * {

display: block;
position: absolute;
top: 50%;
left: 50%;
width: unit(@item-size, px);
height: unit(@item-size, px);
margin: unit(-(@item-size / 2), px);

@angle: (360 / @item-count);

.cl(@i,@r) when (@i > 0) {

&:nth-of-type(@{i}) {

transform: rotate(@r * 1deg)  translate(unit(@circle-size/2,px)) rotate(@r * -1deg);

}

@rot: @r + @angle;
.cl(@i - 1,@rot);

}

.cl(@item-count,0);

}

}

 

CSS Click Event

So you have click the link to find out, how on earth is there a CSS Click Event that I have not heard of? Well that’s because there is no Click Event directly, but we can replicate that event with CSS. Below will show you with a simple example how to action CSS on a click.

As I have said there is not real Click Event in CSS, but you can use the other tools you have to replicate that event. In CSS you can determine the stat of elements on the screen and so with that you can check the stat of a Checkbox. This is how we are going create the Click Event.

You can use the pseudo attribute ‘:checked’ to determine is the Checkbox is checked or not. If you use the pseudo then all CSS under it will only action when it is checked.

 

input{
    background-color:red;
}
input:checked{
    background-color:green;
}

 

Now that we know we can click on an Checkbox to activate CSS, we will need to expand its reach. If you are to click on a menu item of a button, you don’t want it to be a Checkbox. We get round this with the label element. With this element you can surround your items that will change. You can link the input and the label together so when you click on the label you are also clicking on the input.

 

<label for="chk" >

<input type="checkbox" id="chk" />

<span>

<!-- content -->

</span>

</label>

 

From this you can change the style depending on the checkbox state, but with CSS you can only target the children elements. This means you can’t target the ‘span’ because its not a child on the input that is having its state changed. What we can do is target the next element. We can do this by using the ‘+’. If you put this next to the input element then add the span in CSS the it will target the span. It affects the next element to the one on the left, please see the example below:

 

#chk:checked + span {

/* Checked Style Here */

}

 

Now you can put it all together and create a click event like I have in the Codepen below:

http://codepen.io/purerandom/full/mEyqmR/

Visual Studio Code Cookie Snippet

If you didn’t know, Microsoft release an editor called Visual Studio Code and if you didn’t know, Visual Studio Code can handle Snippets and extensions. These Snippets can be created by Visual Studio and by the coding community. These can be simple modules to help coding or full languages. I have found a use to generate a snippet of code that I always use and so I have made this into a Visual Studio Code Snippet. Read on to find out what and how to use it.

What is it?

The Snippet is called CookieJs and by the title you can guess it is about cookies in JavaScript. This snippet produces 3 methods for running cookies. One is to set a cookie, one is to get a cookie and finally a method to check if an cookie exists. These three methods can be produced separately, plus also it can be produced as a JavaScript object.

How do you get it?

If you download Visual Studio Code first of course and you can do the following

  1. Install Visual Studio Code 0.10.1 or higher
  2. Launch Code
  3. From the command palette Ctrl-Shift-P (Windows, Linux) or Cmd-Shift-P (OSX)
  4. Select Install Extension
  5. Type CookieJs
  6. Choose the extension
  7. Reload Visual Studio Code

 

How do you use it?

So like most snippets, it is easy to use. You simply have to type in one of the 4 keywords and they will produce the respective snippets of code.

 

'cookieobj' for full CookieJs object

'chkcookie' for Check Cookie Function

'getcookie' for Get Cookie Function

'setcookie' for Set Cookie Function

 

CookieJs

 

A little snag that kept getting me is to remember to have the language setting set to JavaScript. To change this you need to click the Language Indicator, which is down in the bottom right hand of the status bar. This will bring up the Command Palette for Select Language Mode. You can read more about the languages here on Visual Studio Code site on Languages.

 

Screen Shot 2016-04-27 at 20.18.15

You can get this snippet and more from this link here to my CookieJs.