Programming (back-end), Programming (front-end)

Czy można ignorować testy?

Wiele razy słyszałem, że jak ma się ignorować testy to już lepiej je usunąć. Dlaczego? Bo bardzo łatwo podjąć decyzję o zignorowaniu testu (dodaniu jednego atrybutu czy tam literki “x” w przypadku JavaScript) a trudniej podjąć decyzję o od-ignorowanie testu. Tutaj znajdzie się już milion powodów, żeby tego nie robić: a bo nie ma czasu, a bo to trzeba zmienić coś innego co już działa, a bo ten test to od początku pisała jakaś ciamajda i trzeba go przepisać i to potrwa.
A więc czemu usunąć? Bo i tak nie są uruchamiane i starzeją się z każdą chwilą. To jest “Dead code” który przy okazji maskuje inny “dead code” (normalnie na klasie dostalibyśmy “0 references”, ale przecież jest używana w tym martwym teście).

Continue reading

Programming (front-end)

JavaScript/TypeScript unit testing –11 sample projects for Resharper, Chutzpah and Karma


An example is worth a thousand words. But seriously it’s a lot easier to follow some given scenario than searching for tutorials for some tools and then trying to apply them to a project that is not supported in the end. Moreover unit testing the client side of the project is more complicated than the back-end part. Maybe it’s because we’ve got used to creating test projects based on nunit/xunit/mstest/mspec etc. In Javascript world it’s a little bit more tangled: we have Javascript but also move forward to TypeScript. We have plain code without modules or use requirejs to benefit from AMD. For each configuration the setup of unit test project is different. I think having all these samples in one place could help us to start TDD in client-side.
All the sample are based on the sample application from my previous posts about unit testing JavaScript. Actually these are not 11 different sample projects, but 11 versions of the same project so that you can easily catch the difference between the configurations.

Samples (links)


JavaScript JavaScript TypeScript TypeScript
Resharper link link* link** (none)**
Chutzpah link link link link
Karma link link link link

** Resharper 8.2 should support support TypeScript testing [RSRP-394249]

* AMD support in this sample is artificial, code must be based on named modules that are loaded staticaly.

Tools review




Resharper lets you run unit test for JavaScript. Actually it could be enough to just start using it as a test runner. It’s awesome to right-click on solution, choose “run unit tests” and watch the solution passing all the tests: back-end and front-end in one go. Moreover it’s also super-easy to set up. Unfortunately the practice is more cruel – it’s ok for simple Javascript project without AMD.  TypeScript support is not yet in live and AMD support is not yet even planned. And there is no command line runner to let the tests run in buildserver. Otherwise it would be the perfect choice.



As an alternative we have Chutzpah. To integrate it with Visual Studio  you can install “Chutzpah Test Runner Context menu Extension” or “Chutzpah Test Explorer Adapter” (default one for Visual Studio). You can also download command line tool that will run the tests in console or in buildserver (it even generates code coverage report). It has builtin support for requirejs and TypeScript. Unfortunately tests discovery is a little bit too slow to run it spontaneously after each change.



This runner is a must-have in AngularJS world and is a JavaScript alternative to NCruch (runs tests continuously after saving changes). It’s a little bit tricky to configure but after that it is super cool to play with. It doesn’t have TypeScript support out of the box, but because TypeScript is compiled to javascript it deals with it successfuly. It’s possible to configure karma to use Chrome (or any other favourite browser) to be the test runner and it makes it very fast and natural to debug. It’s also possible to set the “run once” mode to run it on buildserver using phantomJS. The dark side of the tool is that it’s not integrated with VisualStudio and you have to stuck with console window (actually there is one plugin that runs karma in VS output window but it’s still a hidden console and not Test explorer adapter).

Happy testing folks!

BTW: if you like the samples, remember to leave a github star 😉

Programming (front-end)

Unit testing JavaScript with VisualStudio and Resharper – running on buildserver + code coverage using Chutzpah


Unit tests are priceless but only when run automatically. Otherwise they can become forgotten and stay red (or ignored) for the rest of their lifetime. In the last two posts about unit testing in Javascript [1, 2] we have prepared our solution. Now it’s a very good time to tell our buildserver to run them during the build process. I chose Chutzpah as the test runner.


Chutzpah, pronounced [hutz-pah] from Yiddish/Hebrew, means “shameless audacity, utter nerve”. It’s a JavaScript tests runner that uses internally PhantomJS, Jasmine/QUnit to run the tests and BlanketJS to generate code coverage. The package contains both VisualStudio extension to run the tests (but I prefer Resharper) and console runner used by buildservers (especially TeamCity). Beside its core functionality chutzpah can also generate report with code coverage of JavaScript. Among all known approaches to run javascript test, in my opinion using Chutzpah is the simplest.

Getting started with Chutzpah

  1. Download Chutzpah and extract it to some well-known place (in my case C:\BuildTools\chutzpah)
  2. Add chutzpah.json configuration file to the test project folder. This step is optional for chutzpah, but in our case we use root path while referencing files in unit tests and this needs to be configured specially in the config file (there is also some additional information about code coverage pattern):3
  3. Run chutzpah console runner with parameters:
    /path – place where all the testes are
    /codecoverage – tell chutzpah to generate html report with code coverage


There is also an extra output file with code coverage information:


Preparing package for build server

Now we are able to run tests on build server – just run chutzpah.console.exe with specific parameters. the build should fail if any test fails. The other thing is the reporting to the build server about the test result. Fortunately Chutzpah has built-in support for TeamCity (/teamcity command line swith) but also serves XML output (/junit switch).

To have it on Teamcity I needed only to prepare MSBUILD file with the build procedure (I prefer to have everything in source control, especially build procedure, that’s why I don’t believe in TeamCity build steps):1

After adding this file to TeamCity we should see:


And after configuring report tab for “JS Code Coverage”:


Have fun!


Download and play with the demo solution:

Programming (front-end)

Unit testing JavaScript in VisualStudio with ReSharper – improvements

This is another approach to the previous subject: Unit testing JavaScript in VisualStudio with ReSharper. I kindly encourage you to get back to it before further reading.

Referencing production code in Test project

Last time I suggested “link-referencing” files with production code. Then during the build process files were copied to the test project. This approach was a bit cumbersome:

  • we had code duplication in our solution structure
  • sometimes it wasn’t obvious which file was edited – original file or the file copied to the test project
  • R# was complaining about missing references before the build process
  • You need to prepare test project file (.csproj) to make it work
  • You need to reproduce reference structure and keep it up-to-date while working with tests

Fortunately there is a cleaner approach to referencing production code. The solution is to reference files using root reference path:image

In this case we get the root of the test project, go to parent folder (..) and take the files directly from the project with production code (FrontEndTools). Now the only disadvantage is that each test file should know what’s the name of the folder of the tested project and change it when the folder name is changed – but this is very rare case, isn’t it?

If your Resharper marks the referenced file red, add reference to the tested project (FrontEndTools in my case).

From now on the solution structure looks much cleaner:


Switching to Jasmine

Previously I mentioned that I prefer QUnit with its TDD style, but after some time using both I changed my mind. Here are some of my thoughts:

  • Jasmine is more popular – I don’t have any statistics, this is just my feeling after browsing some open source projects and mixing with angularJS communities – I’ve just found Jasmine as a standard
  • Jasmine with its beforeEach/afterEach is more similar to NUnit SetUp/TearDown
  • Jasmine has own (extendable) matchers that simplifies doing even complex assertions
  • Built-in mocking framework is awesome – and this is actually killer feature – in QUnit you should build mocks manually or add external libraries (like SinonJS)
  • Both are supported by default (and only these two) by Resharper
  • Both have very good support and community background (with plugins and extensions)

Other demo solution improvements

  • jasmine.js referenced to test scenarios – Jasmine is by default supported by Resharper, but to get IntelliSense and get rid of Resharper annotations it’s good to reference proper Jasmine.js file explicitly
  • added tests for ColorBoxViewModel with a sample of Jasmine mocking


You can download the demo here:

Programming (front-end)

Unit testing JavaScript in VisualStudio with ReSharper

imageCurrently a huge number of projects is driven by TDD. There are tests of Services, Repositories, Domain objects etc. The attitude to these kind of practices changed and now it’s nothing exciting but our bread and butter. Moreover the architecture of current Web Applications changed as well. In average we spend more than 50% of our time developing front-end side of the app (JavaScript etc) but having in mind, that TDD is only applicable to back-end code. As a ReSharper user I’ll show how easy it is to set up a proper solution with another level of unit testing.


Test application

Let’s imagine that we are doing a web application supporting front-end developers. Among all the functionalities we have a simple reusable module to recalculate color values: RGB/HEX.


Separation of Concerns is one of the most important things while doing TDD, that’s why I chose “KnockoutJS” as the framework connecting our view with the logic. Architecture of such application is very simple. At the moment we don’t even have any “back-end” code, but still can do TDD.


The first test

Let’s pick out the ColorCalculator as the target. This is a “class” that is responsible for calculating color values between RGB and HEX.

Thank to Resharper 6+ we have JavaScript test runner provided out of the box. We can write JavaScript tests with two frameworks: QUnit (TDD style) and Jasmine (BDD style). Here I chose QUnit but you can see version with Jasmine in my next post: Unit testing JavaScript in VisualStudio with ReSharper – improvements. Because these two framework are supported by default, we don’t even have to download/reference any additional libraries. This is how our basic test will look like:


Immediately after closing the test() function resharper will add “Run test” button on the left. In case of QUnit Resharper will run the test in the default browser using QUnit default template, showing the result as it is:


Test result is also shown normally in ReSharper “Unit Test Sessions” window.

Extracting test project

Of course it’s not the best choice to have tests shipped with production code. For most of modules for back-end code we have dedicated “.Test” project. Now let’s extract such a separate project for JavaScript test code.

First add a new project to the current solution. The project type should be “Empty Web Application”  (in contrary to normal unit test project when we add “Class library”). Then you can add your test files to the project. You also need to reference the tested code. To do it, add existing script files as “links”:


This is the drawback of our solution. Whole reference tree needs to be reproduced . But it’s not that bad, we don’t change the reference tree that often but instead we have all the code in one place and it’s checked during the build time. Complete test solution should look like that:


Next you need to do a little trick to copy referenced files to the solution. To do it “Edit project file” and add the following code to the end of the test project:


I hope in the next releases of Visual Studio such behaviour will be applied automatically.

Finally modify a little the test code adding a reference to the code under testing (/// expression):


And that’s it! – after adding some tests and implementing the functionality correctly you can right click the solution, click “Run all tests” and be sure that everything is correct!

UPDATE: There is also better and simpler approach to reference production code. I write about it here: Unit testing JavaScript in VisualStudio with ReSharper – improvements

Debugging the tests

Wiseman said: “If you need to debug unit test then something is wrong with it’s unitness.”

PS: If it’s really needed you can debug it in browser as you normally debug JavaScript code.

Switching to PhantomJS

If you don’t want to run the tests in browser you can run it with headless PhantomJS runner (also by default supported by ReSharper). Go to “Resharper –> Options –> Unit testing –> JavaScript Tests” and change the “Run test with” option:


You need to specify the path to PhantomJS that can be downloaded from here.

Further reading

I write also about some improvements in this area (Test framework, Mocking, Referencing production code) and integrating JavaScript unit testing with our build server:
Unit testing JavaScript in VisualStudio with ReSharper – improvements
Unit testing JavaScript with VisualStudio and Resharper – running on buildserver + code coverage using Chutzpah

Download and play

You can download the whole solution here:

There’s still a lot to do – you can add tests to the ColorBoxViewModel and test “toRgb” function that is far more interesting.
Happy testing!

Programming (front-end)

jQuery Tag-it–autocomplete with grouping


For many people tag-it is the most recommended tag editor plugin. I tried and I can wholeheartedly confirm.
Last time I had a requirement to add grouping to autocomplete list and I’d like to share my solution with you.


Pretty obvious and awesome feature of tag-it is that it’s built upon jQuery UI Autocomplete widget which is nicely documented and configurable. Tag-it expose “autocomplete:” as one of it’s options which means that you can bind to all of its events and customize its options as you wish.

To put grouping to autocomplete list you need to override one of the methods that autocomplete widget uses to render the list. Here is the vital part – full demo will be shown in the end of the post:

    var availableTags = [
        {category: "favourite", label: "c#",         value: "c#", },
        {category: "favourite", label: "JavaScript", value: "JavaScript"},
        {category: "other",     label: "c++",        value: "c++"},
        {category: "other",     label: "c",          value: "c"},
        {category: "other",     label: "Java",       value: "Java"},
        {category: "other",     label: "J#",         value: "J#"},

    var customRenderMenu = function(ul, items){
        var self = this;
        var category = null;
        var sortedItems = items.sort(function(a, b) {
           return a.category.localeCompare(b.category);

        $.each(sortedItems, function (index, item) {
            if (item.category != category) {
                category = item.category;
                ul.append("<li class='ui-autocomplete-group'>" + category + "</li>");
            self._renderItemData(ul, item);

        autocomplete: {
            source: availableTags,
            create: function () {
                //access to jQuery Autocomplete widget differs depending
                //on jQuery UI version - you can also try .data('autocomplete')
                $(this).data('uiAutocomplete')._renderMenu = customRenderMenu;

In tag-it initialization block I override the default autocomplete _renderMenu function. I can agree that this can be considered as smell – overriding private (by convention) method, but to keep things simple it’s pretty clean solution.

“customRenderMenu” method is simple and I don’t feel a need to explain it. Just keep in mind, that this implementation assumes that you pass “category” as a different property of autocomplete item and the source list is initially ordered by categories.



Here’s a link to jsFiddle where you can try the given code: demo

Programming (front-end)

Chrome tips part 1 –selectors


Howdy! After some time I’d like to start with some JavaScript stuff.

Today’s browsers give us excellent opportunity to debug our pages with the one and only Web language which is JavaScript. Best example of that tool is Chrome console which gives us more than could be described in any post. As probably each of us knows, the console opens after pressing F12.


$$ alias

The most common usage for the console is jQuery programming – we can easily traverse the page searching appropriate element or just testing selectors before scripting. The scenario complicates when there is no jQuery included.

Google Chrome console treats $ as an alias for document.getElementById and the result of such queries are far from the desired outcome. Fortunately there is a nice alternative for it which is “$$” alias.

$$ is alias to document.querySelectorAll function that does pretty similar work as jQuery.find method. So everytime I feel the lack of jQuery I use this thing with success. Remember that it doesn’t implement all the selectors that jQuery has (like :first, :even) for argument/classes queries it is enough.


As jQuery.find method replacement we can also use “querySelectorAll” method.

$x alias

Another great tool traversing the document to find some element is $x method. It uses XPath istead of css selectors. It’s good new especially for people who can do more with XPath than with jQuery.


How about ability to deal with iframe’s?

$$ and $x does not search for the content of “iframe” element. To do it you have to switch the search context. To do it with $$ once more you have to use the full name of querySelectorAll method but in context of specific “iframe” document:


In case of $x it’s is slightly different – you have to pass context as a parameter:


You have to remember, that this kind of scripting have to adhere crossframe-scripting policy – domain of the frame should be the same as parent context’s domain.