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.
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.
