Pages

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




Prerequisites


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
  • QUnit - Get both js and css, and place them under a Scripts/libs/qunit.
Sinon.JS
  • 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.
JSTD
jQuery
  • 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: ""

load:      
  - 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

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

52 comments:

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

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

      Delete
  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
    https://www.garmentembroidery.co.uk/
    https://schoolwearcentres.com/

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

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

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

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

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

    ReplyDelete
  8. 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!

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



    nanogramme

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

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

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



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

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

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

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

    ReplyDelete
  17. Marvelous posting this is from you. I am genuinely and truly eager to scrutinize this brilliant post. You've really charmed me today. I believe you'll continue doing all things considered!



    installation including air conditioning

    ReplyDelete
  18. hi, i think that i saw you visited my weblog hence i got here to “go back the
    desire”.i'm attempting to find matters to enhance my internet site!I think its
    ok to use some of your thoughts!!


    먹튀 폴리스

    ReplyDelete
  19. This blog will be very attraction to me .I surely like this newsletter and your writing capability will be very first-rate and beautiful.
    thank you a lot for the good language.



    먹튀검증업체

    ReplyDelete
  20. I commonly visit this web page to observe the activities and works and from time to time for belongings. although,
    it's been a while which you have shared a few report approximately maximum current or up and coming activities



    토토사이트

    ReplyDelete
  21. I at remaining located elegant submit right here.i can get again right here. I simply introduced your blog to my bookmark
    districts. thank you.best offers is the key on welcome the guests to go to the web page, this is the issue that this website
    web page is giving



    토토갤러리

    ReplyDelete
  22. Very nice content thanks very a lot for writing such an thrilling article on this subject matter. This has honestly made me assume
    and that i desire to study extra.



    아띠 토토

    ReplyDelete
  23. thank you for posting this kind of splendid article! i discovered your website best for my desires. It includes
    first-rate and useful posts. preserve up the best paintings!.thanks for this splendid Article!

    안전토토

    ReplyDelete
  24. Heavenly posting this is from you. I am really and genuinely anxious to examine this splendid post. You've truly enchanted me today. I accept you'll keep doing taking everything into account!



    Daycare for Dogs


    ReplyDelete
  25. I just couldn't leave your web site before disclosing to you that I actually delighted within the pinnacle quality statistics you
    gift for your visitors? could be again once more frequently to determine the reputation of latest posts.


    financial advisor NYC

    ReplyDelete
  26. i am glad to locate your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept.
    thank you for the put up.



    Insurance Broomfield CO

    ReplyDelete
  27. wonderful posting this is from you. i'm definitely and certainly eager to scrutinize this super post. you have
    honestly charmed me these days. I believe you'll maintain doing all things considered


    Disc Golf Putters

    ReplyDelete
  28. When you come to Daytona Beach and stay in a Sunlit Vacation Home, it is impossible to be bored! Everything from the Daytona International
    Speedway and it's famous Daytona 500, all the way to the great shopping and miles of beaches. Whether you are coming with family, friends,
    or just a quick getaway, you will find activities and attractions no matter the occasion.


    Daytona Beach Vacation Rentals

    ReplyDelete
  29. Find answers to your auto financing questions at Fikes Chevrolet. We offer a large range of Chevrolet financing solutions.



    Tahoe

    ReplyDelete
  30. huawei p30 price in bangladesh
    Thank you for the sensible critique. Me & my neighbour were preparing to do some research about that. We got a good book on that matter from our local library and most books where not as influensive as your information

    ReplyDelete
  31. Bruc Bond endeavor to lead the financial sector with sustainability, customizable product offering, and open communication. At Bruc Bond we aim to make 21st century banking straightforward, simple, and transparent.



    Bruc Bond


    ReplyDelete
  32. Our expertise in the industry grants us the knowledge and skills to take on even the toughest shipping and logistic challenges.


    Shipping logistics

    ReplyDelete
  33. Nasal Dilator
    I ‘d mention that most of us visitors are really endowed to exist in a fabulous place with very many wonderful individuals with very helpful things.

    ReplyDelete
  34. Cross-border payment is a term alluding to exchanges including people, organizations, banks or settlement establishments working in at any rate two unique nations.




    eyal nachum

    ReplyDelete
  35. samsung galaxy s10 price in malaysia
    The web site is lovingly serviced and saved as much as date. So it should be, thanks for sharing this with us.

    ReplyDelete
  36. Fintech is a term used to describe financial technology, an industry encompassing any kind of technology in financial services - from businesses to consumers. Fintech describes any company that provides financial services through software or other technology and includes anything from mobile payment apps to cryptocurrency.




    B2B Fintech

    ReplyDelete
  37. thanks for this fascinating post, i'm satisfied I found this website on Google. no longer simply content material,
    in truth, the entire web page is splendid



    WordPress Automatic Plugin Nulled

    ReplyDelete
  38. This specific is generally clearly basic and in addition exceptional truth alongside without a doubt reasonable and besides in fact valuable My business is seeking find ahead of time intended for this particular helpful stuffs



    large globes

    ReplyDelete
  39. This specific is generally clearly basic and in addition exceptional truth alongside without a doubt reasonable and besides in fact valuable My business is seeking find ahead of time intended for this particular helpful stuffs



    large world globes

    ReplyDelete
  40. 먹튀검증
    This blog contains so many interesting stuff that makes me want to visit again and again. Look forward for more interesting updates..

    ReplyDelete
  41. 토토사이트
    I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at at this place

    ReplyDelete
  42. Web streamlining implies the path toward making a website continuously perceptible on a web crawler's results page. To clarify, a staggering SEO philosophy will put an association's site at the top of the summary on a Google search page, along these lines improving the likelihood that people will visit the site.



    https://5euros.eu/service/123184/modeliser-une-simple-sous-solidworks

    ReplyDelete
  43. 귀하의 웹 사이트 나 블로그가 처음으로 활성화되면 흥미 진진합니다. 그것은 당신이 당신과 당신의 것 외에는 아무도 깨닫지 않는 것입니다. 먹튀검증

    ReplyDelete

  44. Watch Pinoyflix Pinoy Tambayan Watch all your favorite Pinoy Lambingan And Lambingan for free. Pinoy Entertainment shows Pinoy news shows, Pinoy Tv Drama replay, Pinoy Teleserye Replay, Pinoy Tv, Pinoy Channel, Tambayan At Lambingan, Pinoy Entertainment Replays.Pinoytambayan

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

    ReplyDelete
  45. A decent blog dependably concocts new and energizing data and keeping in mind that understanding I have feel that this blog is truly have each one of those quality that qualify a blog to be a one. 토토커뮤니티

    ReplyDelete
  46. usually i do no longer examine article on blogs, however i desire to say that this write-up very forced me to try to accomplish that! Your writing fashion has been amazed me. Thank you, quite splendid article. woah! I’m genuinely gambling the template/challenge of this internet website. It’s clean, but powerful. Masses of times it’s difficult to get that “high-quality stability” amongst top notch usability and visible appearance. I've to say you’ve completed a remarkable undertaking with this. Additionally, the blog hundreds notable short for me on opera. Extraordinary blog! I truely want to present a massive thumbs up for your remarkable information you’ve were given proper right here on this put up. I’ll be coming lower back all over again for your website for hundreds greater speedy. Took me time to take a look at all the remarks, but i virtually loved the article. It proved to be very beneficial to me and i'm sure to all the commenters here! It’s generally great at the same time as you can not only be knowledgeable, however additionally entertained . I experience quite joyful to have seen your website internet web page and anticipate one of these massive range of all of the more engaging instances perusing right here. An lousy lot preferred another time for each one of the factors of interest. Thanks for giving me useful statistics. Please maintain posting accurate information in the future i will go to you regularly. Thanks . 먹튀검증

    ReplyDelete
  47. Unbelievable. This post is written so well and contains each & every aspect that one must have. Project Viewer 365 Enterprise Crack Key is also in same format. Try this one too.

    ReplyDelete
  48. прямого эфира. Только полезная информация. Каждый участник получит 200% знаний для реализации и получения результатов. Wildberries выход в топ

    ReplyDelete
  49. The National Testing Agency will be likely to release CSIR NET 2024 Application Form on the official website. CSIR NET 2024

    ReplyDelete