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

77 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
    Replies
    1. IEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Projects for CSE It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

      JavaScript Online Training in India

      JavaScript Training in India

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  3. https://conceptbb.com/ 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.

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

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

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

    ReplyDelete
  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. https://www.technologiesblogs.com/

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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


    ReplyDelete
  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

    ReplyDelete
  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


    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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


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

    ReplyDelete
  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

    ReplyDelete
  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

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

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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

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

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



    nanogramme

    ReplyDelete
  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

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

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

    ReplyDelete
  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



    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  35. 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
  36. I’m excited to discover this page. I want to to thanks for ones time for this specially incredible study!! I in reality simply
    preferred each part of it and that i additionally have you ever saved to fav to study new records in your site


    행진

    ReplyDelete
  37. 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
  38. i've tested the item shared right here. As a peruser, I honestly love the blog. the whole thing is point by means of point
    within the article. I sincerely love the way in which you have displayed it. You shake for conferring this remarkable article to us


    토토사이트

    ReplyDelete
  39. 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
  40. 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
  41. 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
  42. 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
  43. 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
  44. 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
  45. 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
  46. 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
  47. 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
  48. Extraordinary post.This isn't really awful post and gives full data. I like to examine this post considering I met such a great deal of new genuine elements concerning it really.Thanks loads. I bookmark your web log because of I found bewildering data on your web log, Thanks for sharing.




    Nasal Dilator

    ReplyDelete
  49. 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
  50. We assume that if you are reading this article, then you are doing research into the cities and tourist places that India has to offer.
    India has rich tapestry and abundant variety, there is no shortage of place to visit.



    best places to visit on india tourist visa

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



    Tahoe

    ReplyDelete
  52. What is the most significant thing throughout everyday life?

    It is consistently those significant things in life that we underestimate.
    A huge number of things will ring a bell now, however you will in all probability overlook one. It is so basic but then it decides our lives each second.
    BREATHING!
    Noson® AG has been managing this test since 2013.
    As a Swiss startup, we have helped more than 3,600 individuals inhale ordinarily once more.
    This reaches from proficient competitors with nasal wing suction wonders to individuals with wheezing issues.
    Presently we offer our most recent advancement to the worldwide market so as to support mankind.



    external nasal dilator

    ReplyDelete
  53. 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
  54. Bruc Bond - 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
  55. 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
  56. Our expertise in the industry grants us the knowledge and skills to take on even the toughest shipping and logistic challenges.


    Shipping logistics

    ReplyDelete
  57. 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
  58. 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
  59. 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
  60. 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
  61. Banking is an industry that handles money, credit, and other budgetary exchanges. Banks give a protected spot to store additional money and credit. They offer investment accounts, endorsements of store, and financial records.




    eyal nachum

    ReplyDelete
  62. 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
  63. 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
  64. 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
  65. best offshore investment account
    Wonderful blog post. This is absolute magic from you! I have never seen a more wonderful post than this one. You've really made my day today with this. I hope you keep this up!

    ReplyDelete
  66. Nose congestion: breathe again thanks to Noson
    A stuffy nose is a typical daily problem, especially in the cold season. However, many people are particularly affected by this problem due to anatomical malformations of the nose or functional disorders.



    dilatatore

    ReplyDelete
  67. country inn and suites
    That's what makes you the best. You should keep publishing more articles and you will Such Become One of the best writers ever

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

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

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