Integrating Javascript Unit Tests with Visual Studio – Organizing Your Tests

So now that your javascript is tested, we need work on getting your test results into Visual Studio. The first step is to organize your tests. You probably don’t have one giant C# file for all your unit tests and you probably are going to want different files for your javascript tests. I took an approach discussed by Phil Haack here and extended it a little bit.

The basic idea is to use controller-less views in Razor to rollup all your test files into one nice little index so you can access them all at once.  In my MVC project I create a new Test folder and add a subfolder called TestPages, in the root of the Test folder I have three files I will walk through next

The Index.cshtml is a standard view, with a twist.  Instead of a standard HTML layout of head, body, etc tags, I actually set it up to be a straight XML file.  This is my big addition to the whole take on this type of integration.  It uses some simple file access to get the list of pages in the TestPages folder.  These are the pages that actually contain our Qunit tests.  The Index creates a simple XML document that looks like this

<!--?xml version="1.0" encoding="utf-8" ?-->
<!--?xml-stylesheet type="text/xsl" href="http://localhost:51844/Test/transform"?-->

The transform.cshtml is a simple XSLT that works on the XML that Index.cshtml generates so when you view it in a browser it looks like this.

Clicking one of the pages brings you to that test page in the TestPages folders and runs the Qunit unit tests and displays the results.  This is where the real benefit of your Knockout viewmodels comes in. Because it let’s you right pure javascript and rely on databinding to manipulate the DOM, you can simply include your viewmodel scripts and start unit testing them in your test pages. If you javascript was littered with class selectors and hardcoded ids you would have a much harder time and would probably have to create mock elements on your test pages for all of those elements.

For now, that should all you need to get your tests all organized and runnable in the browser.  From here the next step will be integrating them into Visual Studio so when you run your unit tests you get both native C# or VB test results, but your javascript results as well.

To download a simple test solution, check it out here

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>