Headless JavaScript testing with RequireJS and Chutzpah in Visual Studio

Introduction

I want to share my setup for testing JavaScript code when used with RequireJS in Visual Studio. My goal was to have the JavaScript tests look and feel the same as the C# tests which are executed using ReSharper’s test runner. That is, tests and code preferably separated in different projects, headless execution (no browser), run the test(s) directly from the file under test or from the solution explorer and TeamCity integration.
ReSharper supports JavaScript testing frameworks like QUnit and Jasmine but unfortunately, at the time of writing, not when the code is loaded by a script loader like RequireJS.
The only test runner I found which supports the above requirements is the Chutzpah test runner.

Setting up

The structure of the Visual Studio solution with production code and test code separated is shown here:
VSSetup

 

For each feature/area to test a folder is created (Calculator in the above case) containing the tests and configuration files. Config.js is tells RequireJS the path to the code under test and to external dependencies like jQuery etc. The chutzpah.json config file contains the path to the code under test, the path to Require.js, what test framework to use (here I’m using Jasmine), etc.

The tests need to be wrapped in a RequireJS module passing the name of the module to test:

With this structure in place it’s easy to add tests for a new feature/area. Just copy a previous test folder and make required changes.

Running tests

To run the tests, Chutzpah Visual Studio extensions need to be installed, go to Tools/Extensions and Updates in Visual Studio and search for Chutzpah Test Adapter for the Test Explorer and Chutzpah Test Runner Context Menu Extension. Supported test frameworks like Jasmine and QUnit are installed along with these.

Tests can then be executed either through the context menu in a file or on a project in the Solution explorer and selecting Run JS Tests:

VSContextMenu

or they can be executed through Visual Studio’s test explorer:

VSTestExplorer

Debugging

Sometimes tests fail. To debug a test, just select Open in browser in the context menu and step through the code using the browser’s debugging tools.

TeamCity integration

Chutzpah integrates nicely with TeamCity using the command: chutzpah.console.exe /path Tests.JavaScript /teamcity

Example source code

Source code for the above example is available here.

This Post Has One Comment

  1. Hi,I am using Jasmine and chutzpah for testing a windows UWP app developed using angular and winjs, but i am not able to test the native app features like File Handling (using Windows.Storage.FileIO methods), as windows is undefined since the unit tests run on browser. How can i unit test the native app features?

Leave a Reply

Close Menu