Friday 25 January 2013

Running JavaScript TestCase Unit Tests using JsTestDriver (in WebStorm)

As part of the process of adding more UnitTests to TeamMentor (while using WebStorm) I’m starting to convert some of QUnit Tests written a while back into JsUnitRunner (which I can execute directly from WebStorm’s IDE)

The process is quite easy since WebStorm already supports JsUnitRunner, which is explained in detail in this JetBrains JavaScript unit testing support blog post.

Let’s take a look at what this looks like using the Greeter Sample app:

image

Which can be opened in WebStorm:

image

In there, open the /test/GreeterTest.js file, select the TestCase call, and press Alt+Enter

image

Click OK:

image

And the current project will now support JsUnitRunner:

image

You can click on the blue arrows to run the test(s)

image

But if you try to run them at the moment, you should get this error:

image

This means that there are no 'captured' browsers. The browsers can be ‘captured’ via the JstestDriver Server View:

image

Which looks like this (when no browsers are 'captured'):

image

To capture a browser, you can double click one of the Icons (for example Firefox):

image

Which will open the browser in a waiting for 'UnitTest to run' mode :

 image

Another way to ‘capture’ a browser is to open the http://localhost:9876/capture page:

image

which will put that browser in the waiting for 'UnitTest to run' mode:

image

Now back in WebStorm, we can start the test's execution:

image

Which executed ok, with a couple failed tests.

That fail is on purpose, since the example (from JetBrains JavaScript unit testing support blog post) is designed to make us fix it :)

The test that fails is the 2nd one (called test greet null ):

image

with the problem being that greeter.greet(null) should return null

image

Here is the a fix:

image

which will now execute ok in the 'captured' browsers:

image

Using jQuery in our tests

Let’s say that we wanted to use jQuery in out tests.

We start by adding a jQuery reference to the .jstd file (this could be a local file, if we copied it to the src folder)

image

Then we add a quick TestCase to make sure jQuery is there:

image 

Which should execute ok (if you are online)

 image

Next, let’s add a variation of the greet function, so that it only returns null if the browser is not IE

image

And update the test greet null to use the greet_forBrowser function

image

At the moment, all is good because we are only using Crome and Firefox browsers

image

but if we add IE

image

to the list of JsTestDriver captured browsers:

image

The tests will pass in Chore/Firefox, but fail in IE (which is the expected behaviour)

image

If we change the logic to return null only for IE:

image

the test will now pass in IE and fail in Firefox/Chrome

image