Minimalistic testing in the browser with Riot.js and Mocha

In the last tutorial ( I explained how to test Riot.js tags using Karma, phantomJs and Mocha, that´s works very well to execute the tests from the command line. But there is a more minimalistic approach that doesn’t need Karma or phantomJs, in case you want to execute the tests in the browser. I will use the same test cases from the previous tutorial.

The mocha before hook looked like this:

  before(function() {
    var html = document.createElement('hello')
    tag = riot.mount('hello')[0]

We are going to just change two things.
If we execute this it will not work because the tag will be undefined, we need to use the riot.compile method:

  before(function() { 
    riot.compile(function() {
      var html = document.createElement('hello') 
      tag = riot.mount('hello')[0]

Now we got the tag properly loaded, but still the tests will fail because they run before our tag finish loading.
So to fix this we need to use the done method from Mocha, to wait until the tag is loaded:

  before(function(done) { 
    riot.compile(function() {
      var html = document.createElement('hello') 
      tag = riot.mount('hello')[0]

And that´s it, now our tests will run just fine.
Online version:

Tutorial: Using TDD with Riot+mocha+chai

TDD using mocha+chai to test Riot tags.
Riot is a React- like user interface library
Mocha is a feature-rich JavaScript test framework
Chai is a BDD / TDD assertion library


You can read the tutorial, or just install the repo from

git clone
cd tdd-mocha-chai-riot
npm install

And then just npm test to run the tests.


This is a simple tutorial about how to setup an environment to do TDD (Test driven development) using karma+mocha+chai to test Riot tags and their properties and functions.You are going to need the last version of Node. Download it from here

We are going to use phantomJs because we need to test the DOM, so an easy setup is to use Karma to run the test.


Create a new folder called tdd-mocha-chai-riot and generate the package.json file like this

mkdir tdd-mocha-chai-riot
npm init

npm init will generate the package.json file, it will ask you for some info, use the defaults values. Then edit package.json and add the devDependencies (this is how it will look

  "devDependencies": {
    "chai": "^3.5.0",
    "karma": "^0.13.21",
    "karma-chai": "^0.1.0",
    "karma-mocha": "^0.2.2",
    "karma-mocha-reporter": "^1.2.1",
    "karma-phantomjs-launcher": "^1.0.0",
    "karma-riot": "^1.0.1",
    "mocha": "^2.4.5",
    "phantomjs-prebuilt": "^2.1.4",
    "riot": "^2.3.15"

Or also you can execute this:

npm install chai karma karma-chai karma-mocha karma-mocha-reporter karma-phantomjs-launcher karma-riot phantomjs-prebuilt riot --save-dev


Then we need to create a new file to config Karma, create a new file karma.conf.js with this content

module.exports = function(config) {
    basePath: '',
    frameworks: ['mocha','chai','riot'],
    plugins: [
    files: [
    preprocessors: {
      '**/*.tag': ['riot']
    browsers: ['PhantomJS'],
    reporters: ['mocha'],
    failOnEmptyTestSuite: false,
    singleRun: true  

Then edit the scripts section from the package.json file, so when we run npm test or npm run test it will start karma and execute the tests.

  "scripts": {
       "test": "karma start"

First TDD iteration: a hello tag exists

Each step in the tutorial is related to a commit so you can see the changes.

Let’s setup our first test, create a test folder, create a hello-spec.js file and copy this code

describe('Hello world spec', function() {

Try npm test (or npm run test), to see if karma is running fine, you should see

V 0 tests completed

I added failOnEmptyTestSuite: false in the karma.config.js file because by default Karma returns an error if you have an empty test.

Our goal is to create a tag that prints Hello {name} inside a H1 tag. So to write the test, the first thing we need to do is to create a tag in the dom called ‘hello’. We just use this line
var html = document.createElement('hello') and then we are going to append that node to the body document.body.appendChild(html)
and mount it, like this riot.mount('hello')
This is going to return an array of tags. Since we just added one, we are going to write this to get the mounted tag:
tag = riot.mount('hello')[0]
Then we will check if the tag exist (not undefined and not null) with the mocha method expect(tag).to.exist
So the test code will look like this

describe('Hello world spec', function() {
  it('mounts a hello tag', function() {
    var html = document.createElement('hello')
    tag = riot.mount('hello')[0]  

Run the test again npm test, and of course it will fail with expected undefined to be truthy
So we need to create the tag. To do so, we create a new ‘src’ folder and a hello.tag file with this content:


Run npm test again, and it will pass. So we completed the first TDD iteration.

Second TDD iteration: has a name property

Now that we know that the tag exist we can add also this expect(tag.isMounted) to check if it was mounted, because riot tags have a isMounted property. In general it’s not recommended to have two expectations in the same test, but as we are testing the same behavior I think it’s fine . You can read more here . We can update the expectation description to “mount a hello tag” to describe exactly what we are testing.

The next goal is: given a name parameter, print Hello {name}. We need a property called name, so we can pass it as a parameter (when mounting) and write Hello {name}. Let’s write a failing test like this

  it('has a name property ', function() {
    var html = document.createElement('hello')
    tag = riot.mount('hello')[0]

Run the test and of course it fails. Let’s make it pass. Edit the hello.tag and write this:

  <script> = ''

This way, Riot will know that our tag has a “name” property. Run the test again and it will work.

Refactor: Move duplicate code to before hook

Now that we have confidence that the code is good, let’s refactor it a little bit. As you can see we have duplicate code in our tests. Let’s use the mocha before hook, so it will only execute one time. Move the duplicate code to a before hook, editing the tests

  before(function() {
    var html = document.createElement('hello')
    tag = riot.mount('hello')[0]

Run the tests again, and it should pass.

Third iteration: mounts a hello tag with a setted name

Our next goal is to mount the tag passing the name property. Let´s write the failing test

  it('mounts a hello tag with a setted name', function() {  
    tag = riot.mount('hello', {name: 'Carl'})[0]

It will fail with: expected '' to equal 'Carl', so to make it work we need to use the “opts” functionality that Riot gives us. Just update the hello.tag like this

  <script> =

Run the test again, and the last test pass, but the second test is not working. What´s happening?
This shows why TDD is useful: when we introduce new functionality we can break the old code. So how can we fix this? It´s easy, the problem is that it’s expecting a string, but it’s undefined. So we change the code a little, so if is undefined then we use an empty string.

  <script> = || ''

Run the test again and it should pass.

Refactor: Using karma autowatch to automatically run the tests

Running npm test each time could be a little slow, so we can add autoWatch: true to our karma.conf.js so it will rerun the test each time a file is modified. Also remove the singleRun: true,” line. This will run the tests each time we save the files, so we can have a fast feedback loop when doing TDD.

Now if we ‘run test’ again, karma will wait for changes. Let´s edit a test just to confirm this. For instance, we can change the second expectation to expect(tag.isMounted) and then check the console. karma automatically run the test and shows the failing test. Let´s fix the tests again changing expect(tag.isMounted) and now all tests will pass.

Fourth iteration: prints Hello {name}

Next, we want to show the Hello {name} inside a H1 tag, so let’s write a new test and learn how to use the querySelector method.


Hello {name}

', function() { tag = riot.mount('hello', {name: 'Carl'})[0] var tagText = document.querySelector('hello > h1').textContent expect(tagText)'Hello Carl') })

As you can see we are using document.querySelector('hello > h1').textContent. This will search for a h1 tag inside a hello tag and get the textContent. We don’t need to run the tests because it will run automatically and it will fail. So to make it work we edit the hello.tag like this.

  <h1>Hello {name}</h1>
  <script> = || ''

Now if you check the console all tests will pass.

Fifth iteration: Transform name to uppercase

We can also add functions to our tag and test those functions. Let’s write a simple test that call a custom function called uppercase and expect the name to be converted to uppercase:

  it('transform the name to uppercase', function() {
      tag = riot.mount('hello', {name: 'Carl'})[0]

We have a failing test in line 31, because uppercase is not a function of our hello tag. So let’s create it.
We are going to add a new function called uppercase like this

    this.uppercase = function() {

and now all tests will pass.

I hope you liked the tutorial. We learnt how to setup mocha+chai+karma to test riot tags, how to autorun the tests and how to test Riot tag’s properties and functions.

I hate “how to make a blog in 20min” tutorials

Those tutorials are good to show the potential of the framework when is used by someone that have experience with it. But it doesn’t teach you much about the process of building your own application. And watching a lot of those can damage your perception of the learning curve needed to build something because you think that it’s easy.

I really like the approach of Michaael Haart in his RailTutorial, because he explain all the things that can go wrong and how to solve them. Because that is learning, trial and error. When you start a project by your own, you will have to face a lot of errors.

I told you this because some years ago I tried to learn ruby on rails thinking that it would be easy, I watched the zombie tutorial, tryRuby, and some 20min blog but when I tried to make my own application I felt frustrated and dumb for all the errors that I faced. But then I changed and some month ago I started again, but this time I approached it thinking that I will have to deal with the errors and my own mistakes , and that there is no easy or fast way to learning, just the old Try and Error.

Beat procrastination with Kaizen

The greater the task, the greater the resistence to do it. One way to avoid this is making it in small steps, as small as possible. Do you want to exercise each day for 1hr? Just thinking about it creates resistence, so make a small step, aim to just 1 minute of exercice per day. Maybe while watching TV, or  you can just walk in front of it.

This is Kaizen, a method that you can apply in almost anything. I highly recommend this book  “One Small Step Can Change Your Life: The Kaizen Way

My daily routine consist in 5 minute tasks:

-5m blog writing : Maybe a paragraph.
-5m learning: Some new function
-5m for one of my personal projects: Write some code lines, or fixing a little bug
-5m studying: I like studying with cards, so in 5m  I can make 1 card and reread 3 cards
-5m reading a book: 4 pages

In just 30m per day you can advance in 5 different aspects of your life. It could look small but in a month this means:

-2 o 3 new blog post
-10 new functions
-100 new lines of code and some bugs killed
-30 new study cards  and 30 rereaded
-100 pages readed

And the most interesting thing about kaizen is that thinking about doing the task for only 5 minutes let’s you pass the initial resistance (even thought you might end up spending much more time on it) and enjoy doing something that you might think is dull.

So if you are interested check the book One Small Step Can Change Your Life: The Kaizen Way

Clean Code Book – top 5 tips

Some month ago I read the book: Clean Code, I highly recommend it. Here are the best tips that I found.

  • Boy-scout Law: Leave the campground cleaner than you found it. The cleanup doesn’t have to be something big.  If you have to modify something, try to improve the readability of nearby code
  • Functions:
    • Must be short (5 lines)
    • Better without arguments or less than 2
    • Should do only one thing, do it well, and have no side effects
  • Variables
    • Better with long and descriptive names
    • Be consistent. Don’t use get and retrieve for the same
    • Use constant. Like MAX_NUMBER_LINES instead of just 10
  • Comments
    • It’s better to write a descriptive function than a comment
    • Outdated comments confuse
    • Instead of comment an ugly function, try to refactor it, so it express clearly what it does
  • Classes
    • Small classes (200 lines)
    • Line width < 120

edit: These are my notes from the book “Clean Code” ,Robert C. Martin. I know that some tips are polemic so I wanted to share it to know what others think about it. You can read  clean code articles  by Robert C Martin

edit2: I want to share more info about the “less that 2 arguments” and 5 line functions.

The author says: “The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification — and then shouldn’t be used anyway.”

A really good stackoverflow ‘s thread  about the “5 lines functions”

Today is demo Day!! and then CRASH! (My checklist to avoid it)

Today is demo Day!, you and your team are excited to show to some potential customer, all the awesome things that the new app can do .  The demo start good, but then CRASH!

We all have been there, the bugs like to show up in demo’s day, it’s a software law. But you can avoid it with a simple checklist. This is mine, you can create your own.

1) Before demo don’t touch the code!

This is one of the most common errors. One developer discover a simple bug, then tries to fix it before demo. He fixed it , but he didn’t  test the others 10 scenarios. So of course in middle of the demo, it CRASHES!

protip:  Use Test Driven Development, or at least test your code. So when someone refactor something or fix a bug you have confidence that all the code works as expected

2) Check the demo environment

Sometimes your dev environment is full , there is no more space, so in Demo Time you have a nice error like this: “Storage limit exceeded” . This happened to me when coding some Salesforce Apps.

3) Prepare your demo data

We are awesome and funny coders, we like to put strange names in the records like “ababshaha” or “Bruce Willis” , that is nice but in demo day  it is better to have clean and nice data to show.

protip: While you are coding try to fill the forms with meaningful data. There are browser plugins to automate this or some test tool too.

4) Have a list of what to show (focus on the client).

We like to tell the client that we have an algorithm that work 10 time faster that the old one, but you know what? They don’t care. In demo day focus on the client side, show things that they care. This is usually the opposite of what you care about. For example, you spend two days working on the new and great algorithm to sort things, but the client loved the way that the jquery plugin slideUp some popup (that took you 2 minutes to setup).

5) Bring only the important people to the demo.

If you are the project manager don’t waste developers’ time inviting all the project developers, invite just the ones that can help you.  From client’s side it is also better to have few people invited. If you run the demo using the phone and screen share, it can be really annoying communicating with a lot of people.

I am not a Rock Star developer

Rock is chaos , destruction, go against the order. I love rock and roll but I am not a Rock Star coder

So when I see “ We are a rock band business, ready to take the world, so we need a Rock star developer to rock the world with us”

Well that really turn me off.

If you want to capture  my attention write something like:
“We are two guys and a Girl building our business,  we are looking for a Violinist coder, who execute clean notes, pleasant sounds and harmonious music”