Tuesday, February 12, 2013

JavaScript Unit Testing in Visual Studio Part II

Setting up the Environment for Headless Tests

js test driver
In the previous post, we've set up the scene, by setting the expectations and picking the libraries & tools for the job.

In this post we will take it step-by-step, so you can follow and get active in the process.

So here we go... 


Set Up the Project

  • We'll start by creating an empty Web Project. So, launch your Visual Studio, and create a new Web Project. Select ASP.NET MVC Web Application, name it JavaScriptTesting or whatever makes you happy, and make sure to select an Empty template on the second step in the Wizard.
  • Feel free to delete all items under the Content and Scripts project folders.
    Go even further, and delete the packages.config file automatically added by Visual Studio and the packages folder in the solution root on the disk.
    Just so we can concentrate on what really matters... (Nothing personal against NuGet).
  • Under the Scripts folder,go and create three sub-folders and name them: libs, modules, and tests.

At the moment your solution tree should look similar to the one in the screenshot below.
Nothing special yet, a naked MVC project with minimal elements.

visual studio solution explorer
NOTE: In your development environment you might not like the idea of having the source code and tests under the same project. You can of course place the tests in a separate project, and as the concept of adding a reference to a js file doesn't exist, and we would not want to duplicate source files, you can accomplish that by defining a pre-build event on the tests project to copy all the stuff you wanna test.

In this post, for brevity, a single project holding both source and tests will suffice...

Download the Libraries 

Let's go and grab all the libraries.

  • QUnit - Get both js and css, and place them under a Scripts/libs/qunit.
  • Sinon.JS - Save the js under a sinon folder beneath Scripts/libs/sinon.
  • Sinon Adapter for QUnit - Save it also under the sinon folder.
  • Make sure to also get the Sinon-IE.js. It is for compatibility for IE when Timers & fake XHR is used. While on Sinon.JS site, navigate to the Fake XMLHttpRequest section under the documentation and look for sinon-ie.js.
  • Get a fresh copy of jQuery and also place it under a new folder - Scripts/libs/jquery.
At the moment your solution tree should look similar to the one in the screenshot below, and your solution folder should contain the project folder and the JSTD jar file.

visual studio solution explorer

We will leave Require.js aside for now, to be discussed in a later post in this series.
So, for now, we've got all the libraries we need to start with. 

The Unit Under Test

In order to run unit tests, we first need some kind of unit. So let's create a very simple component to play around with. 

Create a new calculator.js file, under Scripts/modules, with the code snippet below:

var Calculator = function () {
    this.sum = function (num1, num2) {
        if (num1 == undefined || num2 == undefined) {
            throw "Invalid argument";
        return num1 + num2;

This should be enough, as now we can go on and test the sum method.

Unit Test

Next, create a new js file under Scripts/tests and name it calculator-tests.js, with the code snippet below:

module("Calculator Tests", {
    setup: function () {    
    teardown: function () {    

test("Sum", function () {
    // Arrange
    var calculator = new Calculator();
    // Act
    var sum = calculator.sum(2, 3);
    // Assert
    equal(5, sum);

We've created a Module named Calculator Tests, with a single test named Sum, which in we instantiate the Calculator, call the Sum method, and simply Asserts for the expected result.

Configuring JS-Test-Driver

Js-Test-Driver, expects a configuration file in a YAML format. For more about the Configuration File settings see here.

Create a text file in Visual Studio, name it jsTestDriver.conf, and place it in the project root, just next to the Js-Test-Driver jar file.

Copy the snippet below to the file:

server: http://localhost:9876

basepath: ""

  - Scripts/libs/jquery/jquery-1.8.3.min.js    
  - Scripts/libs/qunit/qunit-1.10.0.js      
  - Scripts/libs/sinon/sinon-1.5.0.js
  - Scripts/libs/sinon/sinon-qunit-1.0.0.js
  - Scripts/libs/sinon/sinon-ie-1.5.0.js      
  - Scripts/libs/js-test-driver/equiv.js
  - Scripts/libs/js-test-driver/QUnitAdapter.js      
  - Scripts/modules/calculator.js

  - Scripts/tests/calculator-tests.js  

If you've placed JsTestDriver outside the project, replace the basepath to reflect the path to the folder containing JsTestDriver-1.3.5.jar.
If using other versions of the libraries under the load section, then rename accordingly.

Customize the Tools Menu

We're almost there...

JS-Test-Driver can be executed from the command line, but we wanted seamless integration with Visual Studio, so let's create custom menu entries so we can run those tests with no more than a few keystrokes.

Menu Item for launching the Server

  • Open the External Tools under the Tools menu.
  • Click Add, to add a new entry in the menu.
  • Set "JSTD Server" for the Title.
  • Set the full path to jave.exe.
    In my case it is "C:\Program Files (x86)\Java\jre7\bin\java.exe".
  • Set the Arguments to:
    -jar JsTestDriver-1.3.5.jar --port 9876 --browser "C:\Program Files (x86)\Internet Explorer\iexplore.exe","C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"

    I've set it to run both IE and Chrome.
    Make sure to point to the correct path on your system.
  • Set Initial Directoryto $(ProjectDir)
  • Check Close on exit.
  • Click OK to Save.

It should look similar to the screenshot below:

visual studio external tools

Menu Item for running Tests

  • Open the External Tools under the Tools menu.
  • Click Add, to add a new entry in the menu.
  • Set "JSTD &Run" for the Title.
  • Set the full path to jave.exe.
    In my case it is "C:\Program Files (x86)\Java\jre7\bin\java.exe".
  • Set the Arguments to:
    -jar JsTestDriver-1.3.5.jar --server http://localhost:9876 --tests all --testOutput "jsTestDriver-TestResults" --verbose
  • Set Initial Directory to $(ProjectDir)
  • Check Use Output window.
  • Save settings.

It should look similar to the screenshot below:
visual studio external tools

And that's it.

Running The Tests

  • From the Tools menu, click on JSTD Server.
    It will launch a new command, and you'll see new windows/tabs added to both Chrome and IE.
  • Now go and hit Tools menu, and then JSTD Run, or  just Alt+T+R.
NOTE: When the solution contains more than one project, make sure to select the project before running the JSTD Server or the tests. As the $(ProjectDir) will instruct Visual Studio to look for the the Jar file under the selected project.

Tests will get executed, and you'll be able to see the results in the Output Window:

visual studio output window
You've made it. You have just executed your first JavaScript Unit Tests in Visual Studio.
And you can see that both tests passed.

You should leave the JSTD Server running, and the browsers waiting, and just hit Alt+T+R when changing the code...

What We've accomplished

  • Seamless integration with Visual Studio.
  • Headless testing.Against multiple browsers at the same time. 
  • Support for Async Tests.
    (More about it in future post).
  • Documented libraries & Tools.
  • Free Tools.

What's Next?

In the next posts we will talk about AMD and we will see how to combine JS-Test-Driver and Require.JS to play nicely together.

Have fun testing...


  1. I always had to specify --basePath "$(ProjectDir)" when configuring both JSTD Server and Client in External Tools menu

    1. Hi Nikolay, if it works for you then it sounds like another valid way for configuration.
      I set the initial directory to $(ProjectDir), and inside jsTestDriver.conf I set the --basePath in to an empty string, as you can in a previous post, number 2 in this series.

  2. Schoolwear Centres specialises in supplying school uniforms, with embroidered Logos to schools across UK. Our year –round services saves you time, stress and money.for more info visit Our Websites

  3. Owning a small business is a huge accomplishment and also a burden at the same time. All small business owners know how liberating it can be to break free from the 9-5 and strike it out on your own.

  4. We are the best platform for those who don’t have the learning facility in their area. Our plan is to make the Muslims learn the Holy Book in the best possible manner. We teach with the correct voicing Learn quran online.

  5. Watch Pinoy TV, Pinoy Tambayan website to watch all Pinoy Lambingan Orihinal, Teleserye Replay shows of Pinoy Channel Online. Pinoy Lambingan.

  6. Here, Spinbot is available to rewrite human-readable content. Moreover, if you are not free to write content daily, then you should try our bot to rewrite readable content.

  7. Online Quran Classes for kids to learn the reading, Kids Quran Memorization, Quran lessons for kids and children. Your kids will have one on one attention in online.

  8. Wow Nice Blog Post Amazing Must Visit The Following links Amateur Blogs
    Its Very Helpful for you Amateur Blogging
    Recommended for you Amateur Blog

  9. Noteworthy site, Distinguished criticism that I can handle. Im pushing ahead and may apply to my present place of employment as a pet sitter, which is truly charming, yet I have to extra extend. Respects.

    saint pierre tissu marche

  10. I genuinely had a great time examining your article. I found this as a valuable and interesting post, so I think it is useful and knowledgeable.this is a magnificent blog article.Much thanks again. Sensational.

    saint pierre coton marche

  11. Great blog! Is your subject hand crafted or did you download it from somewhere?A topic like yours with a couple of basic adjustements would truly makemy blog sparkle. It would be ideal if you let me know where you got your structure

    marche tissu pas cher saint pierre

  12. Unprecedented blog! Is your subject hand made or did you download it from somewhere?A theme like yours with a few key adjustements would genuinely makemy blog sparkle. You ought to uncover to me where you got your structure

    asic miner

  13. I truly expanded some outstanding experiences looking over your article. I found this as a basic and spellbinding post, so I think it is huge and knowledgeable.this is an awesome blog article.Much thanks again. Stunning.

    salle de sport vincennes

  14. Extraordinary information! I as of late ran over your blog and have been perusing along.
    I figured I would leave my first remark. I don't have a clue what to state aside from that I have.

    salle de sport vincennes

  15. A devotion of thankfulness is all together for all the effort in sharing this stunning post and I genuinely to invite it. Your commitment and solid work has helped you to pass on stunning quality articles everything considered

    s17 antminer

  16. e commerce nanogramme
    Your blogs further more each else volume is so entertaining further serviceable It appoints me befall retreat encore. I will instantly grab your rss feed to stay informed of any updates.

  17. You finished sure dependable focuses there. I completed a pursuit regarding the matter and located about all and sundry will concur together with your blog

    Huawei Mate 20 Pro Mobile Phone Price in Sri Lanka

  18. I found your site perfect for me. It comprises of great and helpful posts. I've perused a considerable lot of them and furthermore got such a great amount from them. I would say, you do the genuinely amazing.Truly i'm intrigued out of this distribute

    mailjet nanogramme

  19. créer une application nanogramme
    I was very impressed by this post, this site has always been pleasant news Thank you very much for such an interesting post, and I meet them more often then I visited this site.

  20. agence digitale
    I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at at this place

  21. Very nice content thank you very much for writing such an interesting article on this topic. This has really made me think and I hope to read more.

    site marchand nanogramme

  22. site vitrine nanogramme
    Always so interesting to visit your site.What a great info, thank you for sharing. this will help me so much in my learning

  23. I found your site ideal for me. It contains extraordinary and supportive posts. I am pretty well pleased with your good work. Looking to read your next post.

    agence digitale paris

  24. site e commerce nanogramme
    A very nice and good post this. I really like it very much. Keep this quality of your work on articles going on and please do not let the quality of your articles fall to bad. Cheers!

  25. Thankful for granting such magnificent information to us. Kaspersky Login is a basic, clear and straightforward procedure. Regardless, once in a while you may get the Kaspersky login botch. This screw up can be appeared considering a couple of reasons.


  26. I am pretty much pleased with your good work. Very nice content thank you very much for writing such an interesting article on this topic.

    créer une application android nanogramme

  27. créer une application mobile nanogramme
    Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.

  28. application web nanogramme
    Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one.

  29. Appreciative for giving such wonderful data to us. Kaspersky Login is an essential, clear and direct method. In any case, on occasion you may get the Kaspersky login mess up. This botch can be showed up thinking about two or three reasons.

    creation site e commerce nanogramme

  30. Grateful for giving up such magnificent data to us. Kaspersky Login is a central, clear and direct structure. In any case, by and by

    moreover, again you may get the Kaspersky login mess up. This chaos up can be appeared contemplating a couple of reasons.
    développement application mobile nanogramme

  31. sous traitance web seopublissoft
    Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

  32. precise stuff! Congrats for making it viable for growing this blog. i'm strongly trust your posting cloth and need to want to mention
    thank you for making this put up right here

    Latest Google Pixel Mobile phone price in Malaysia

  33. I need to a large portion of the facts, I must guarantee when I loved, when I would really like extra facts recognized with that,
    on account that it's especially superb., recognize it about uncovering

    ë²³ 365

  34. hello, I discover scrutinizing this text a pride. it's miles distinctly useful and fascinating and specially envisioning analyzing a
    more noteworthy degree of your paintings

    Latest HTC Mobile phone price in Singapore