Unit Testing JavaScript with MSTest and JSTest.Net

JavaScript: A necessary evil

I’ve always found that while JavaScript was a powerful tool for web development it could be a real pain to test and debug.  Until now I pushed through the pain with good old fashioned manual testing and the debugging tools available in web browsers.  Recently, I was developing a web page that needed a lot of client side calculations and data manipulation. I decided it was time to man up and find a way to unit test client side JavaScript.

I Wanted

  1. Integration with MSTest
  2. Writing unit tests with server-side code as I do for C# code
  3. Running JavaScript and C# unit tests together in harmony
  4. Nothing to install so others can just start using the testing library
  5. No web browser required

Surprise and Delight
A few minutes on Google and I found a solution that appeared to be the answer. Before I go on, I should mention I found several testing libraries so there are many options. Most of which integrate with MSTest and most other testing frameworks.

The winner is
I selected to use JSTest.Net

It was pretty simple to get up and running:

  1. Just download the dll from JSTest.Net
  2. Made a reference to it in my test project
  3. Added a couple using statements in my test class
  4. Started writing tests

Consider this JavaScript example

function calculateMarketPrice(value, quantity, factor) {
    return (value / quantity) * factor;

It’s pretty simple, send in a few parameters and return a value.  However, testing this manually and debugging through the web browser is not always as simple, especially if it’s implemented on complex web pages.  In a lot of cases it’s tedious and inefficient.  Even worse it could be ineffective and bugs could be missed.  For example, maybe there’s a rounding issue?  Or maybe a null parameter won’t be handled as expected.  We just don’t know unless we test for it.  And when testing is difficult it’s more likely to be missed or god forbid skipped.

Test Class Example

using Microsoft.VisualStudio.TestTools.UnitTesting;
using JSTest;
using JSTest.ScriptLibraries;

namespace JavaScriptTestProject
    public class CommonJavaScriptTests
        private readonly TestScript _commonTestScript = new TestScript();

        public CommonJavaScriptTests()
            _commonTestScript.AppendBlock(new JsAssertLibrary());
        public TestContext TestContext { get; set; }

        public void GivenValueQuantityAndFactorTheCorrectMarketPriceIsReturned()
            _commonTestScript.RunTest(@"assert.equal(99.26, calculateMarketPrice(49630, 50000, 100));", true);

A quick overview
The library uses a class called TestScipt as a wrapper  to command line scripts (CScript). Before writing tests it’s necessary to add the script file you’ll be testing and any additional libraries to the TestScript.   In my example I used the AppendFile method to add my js file and the AppendBlock to add the assertion library included with JSTest.   According to the documentation there are other assertion libraries and mocking libraries available but I have not tried them yet.

Once the scripts are appended to the TestScript class the RunTest method can be invoked.  It takes the script block to be tested as the first parameter and has an overload that includes a boolean to turn debug off and on.  When debug is on and you select to debug your test it allows you to step into the debug test script and from there into your script. This is awesome. Not only do I get to easily test every scenario I can think of, I get to debug it too!

JsTest Documentation

Other Things

  • My example uses MSTest but it works with other test frameworks
  • The documentation says it only works with VS2010, But I have it working in 2008

With testing libraries that are compatible with most frameworks available there are no excuses for not covering JavaScript with unit tests. And the integration with the visual studio just in time debugger is icing on the cake. It’s also worth noting I’ve since used this library for more complicated tests that included date manipulation and JSON and found it just as effective.


About Shawn Sweeney

I'm a father, software developer, and runner. I blog about things related. View all posts by Shawn Sweeney

17 responses to “Unit Testing JavaScript with MSTest and JSTest.Net

  • Nayan Hajratwala

    You should check out Jasmine. Excellent javascript testing. Also check out coffeescript for writing simpler/better javascript.

  • Shawn Sweeney

    Thanks for the comment Nayan. Both of these look interesting, I’ll give them a try.

  • Bogdan

    very nice example. thanks to you i fund out about jstest.net and how to use it and the boss was really happy that it can be integrated in the companies TFS which cannot be said about jasmine. funny thing is this is a great tool yet this is the only place ive seen it even mentioned, everyone else just blindly follows jasmine nowadays. thanks for the info also if you want you can add that it works just fine (as far as i can tell) in VS 2012 as well.

  • Bogdan

    any idea if jstest.net supports external libraries like sinon.js or does it only support the 4 it comes with(jsmockito, jsmock, jshamcrest, json2)?

    • Shawn Sweeney

      I haven’t tried any others, but, you can append any JavaScript file to the test. That being so, I would assume other mocking libraries would work too once appended.

      The documentation is really light in regards to mocking in JSTest. Other than to say you can do it and they include some common libraries.

  • Unit testing CRM 2011 JavaScript web resources | MSDN Blogs

    […] Unit Testing JavaScript with MSTest and JSTest.Net […]

  • coppermillAvery

    At last full TDD can be performed.

    Thanks very much for your post, it make testing JavaScript so much easier.

    One big question I have is JSTest only has 51 downloads on CodePlex, is this a concern or have you found a hidden gem?

    • Shawn Sweeney

      That’s a great question, I’m not really sure why that is. I had the same concern, just seemed like it wasn’t being used much. But, I haven’t had any problems so far.

      One explanation might be that developers are more comfortable with browser based frameworks like QUnit.

      Also, it looks like they’ve had more downloads since moving to GitHub through the NuGet Gallery.

      • Chris Baxter

        Thanks Shawn for the great post on JSTest.NET, I have been meaning to leave a comment and thank you for a while now.

        As for the lower number of downloads, I personally attribute this to the lack of promotion on my part. I have been using this approach to test JavaScript business logic for about five years now without issue. I do think most developers prefer QUnit/Jasmine as that is what is mainstream and I personally have never taken the time to blog about why I think this is a better approach (something I should do).

        As mentioned by Shawn, the core NuGet package does get around 60 downloads per month; I just don’t see a lot of activity on CodePlex.

  • Rajakani Murugesan

    Thanks for the blog, those are the same five requirements I too was looking for.

  • Kulwinder Kaur

    Can we test angularJs apps with jstest.net .if yes then how will we mock things

    • Shawn Sweeney

      Hi Kulwinder. Thanks for your comment/question.

      I don’t think jstest.net is a good fit for testing angularjs apps. Especially anything DOM specific like directives. Possibly you could test some controllers and services depending on what they’re doing. But, even that would be difficult with DI and mocking.

      I’d suggest using Jasmine for unit testing and Protractor for End to End testing. Angular provides the ngMock module for mocking services.

      • Kulwinder Kaur

        Ok Thanks a lot . We are already using jasmine for unit testing .But we are developing UWP app on windows 10 .We are failing in testing our windows native features like Windows.Storage.FileIO since test run on headless browser(we are using chutzpah for that). How can we test our windows features using jasmine.

      • Kulwinder Kaur

        Thanks a lot . We are developing UWP app on windows 10. We are using jasmine and chutzpah but we are not able to test windows native features like Windows.Storage.FileIO since chutzpah runs on an headless browser so we are getting Windows as undefined there. So how can we test our windows specific APIs.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: