QUnit - Client side unit testing with TDD

I've wrote this article a few months ago but in Portuguese: I've decided to translate it to engish. The sample project is hostead at GitHub but it's in Portuguese (the same as my first article).

Link Github: https://github.com/guilhermegeek/QUnitSample

I've been progamming with unit testing and test-driven developement in use for server-side for 2 years. On the last months i've been working more with javascript, so i decided to try this concepts in cliente-side! Of all the frameworks i've seen for unit tests, the QUnit was my favourite. It's also used by jQuery team. For this article i use the scenario where you need to write a method that validate some student code, and you test your code with unit tests.

jQuery (required by QUnit): http://docs.jquery.com/Downloading_jQuery QUnit: https://github.com/jquery/qunit

First lets start by declare our scripts in the head of page. You can use the default theme (.css). It's quite simple and clean.

function OutputJS { this.Msg = null; this.Code = null; }

Use the follow html elements in your page:

Unit Tests

    Now it's time for us to write the first test! For this we'll follow TDD. First we write the test and it should give an error. Then we start writing the code that will be tested, and we run the test to see if the code is already doing what we want (you can check some scenarious using tests like massing requests and bots that are greate!).

    function Should_Validate_StudentCode(studentCode) { result.Code = false; result.Msg = "The minimum length of Code should be 4."; return result; }

    As we already except, the test will fail. This is what we want. As we're using javascript code, the best option for you to run your tests it's in $(document).ready of a page. But if you want you can execute the tests from some plugin or even an server side application.

This article is part of the GWB Archives. Original Author: Guilherme Cardoso

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.