Monday 17 November 2014

Setting up AngularJS, Jasmine, andKarma in Visual Studio

Introduction

I’ve recently been tasked to research AngularJS to use on top of Visual Studio. After reading the official tutorial, unofficial tutorials, and Manning’s early access AngularJS in Action and Getting MEAN (which stands for mongoDB/Express/AngularJS/Node.js), I found that there are too few guides for Windows users. If you’re like me, you probably are running into issues installing and running karma, would like to run Javascript tests in the convenience of the Test Explorer (or Resharper), and want to let NuGet handle all of your package updating (bower is great, but not for .NET environments). Well, this tutorial is here to help! We’ll get you up and running with AngularJS, Jasmine, and Karma.
All of this has been setup/tested on:
  • Windows 8.1 x64 Pro
  • Visual Studio 2013 Professional
  • Google Chrome

Getting Started

Go ahead and install the following software:
Once all of that is setup it is time to set up our project environment. Go ahead and create a new Visual Studio project – you can choose any project you wish; this tutorial will use ASP.NET MVC 5 (by selecting ASP.NET Web Application). Select MVC  and Add unit tests. We’re going to use a traditional view to power our SPA (though, you could easily create a Web API project instead – just make sure that you set your routes up to point to an index.html page instead of an ASPX/Razor view).
Visual Studio project screen
Now, we need to grab a few Javascript libraries from (hint: if you prefer, you can grab these from NuGet): AngularJS (I recommend grabbing the entire ZIP that includes all libraries) and Jasmine (you can use another testing framework if you prefer but the official AngularJS examples/tutorials use Jasmine).
Okay – you have all of the tools either installed (or about to be).

Setting up the project folder

You should have two projects: Your ASP.NET MVC/Web API project and your Tests project. Inside of the ASP.NET project, we’re going to add the following folders: ng-views and ng-scripts.
The ng-views folder will contain all of your Angular-specific views. The ng-scripts folder will contain your controllers, models, directives, and so forth. In the Tests project, create an ng-tests project. If you installed Angular and Jasmine via NuGet you should be able to skip to the next paragraph. Now, extract your AngularJS archive and copy all of the scripts to the ~/Scripts/Angular/ folder (you’ll need to create the subfolder). Unarchive Jasmine and copy the contents of the lib folder to ~/Scripts/Jasmine/. You’ll need to update your /App_Start/BundleConfig.cs file – do that now by adding the following lines to the RegisterBundles method:
bundles.Add(newScriptBundle("~/Scripts/Angular").IncludeDirectory("~/Scripts/Angular","*.js"));
bundles.Add(newScriptBundle("~/Scripts/Jasmine").IncludeDirectory("~/Scripts/Jasmine","*.js"));
Go ahead and right click on the ng-tests folder – you’ll notice that you can run tests using Chutzpah from the context menu – one will load tests into the Test Explorer and the other option will load a static browser instance version of Jasmine.
Finally, if you love IntelliSense (who doesn’t), you’ll want to create a _references.js script in both your ASP.NET project and your Test project. Create a blank Javascript file in both projects, select all of your Javascript files, and drag/drop them into both blank files (or you can also build out the file yourself – up to you). Your _references.js file should look like:
/// <reference path="modernizr-2.6.2.js" />
/// <reference path="jquery-1.10.2.js" />
/// <reference path="bootstrap.js" />
/// <reference path="respond.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
/// <reference path="../Scripts/angular.js" />
/// etc..
Now, with any new Javascript file you create, do the same thing with just the _references.js file to first line of every project. Go ahead and create some baseline files for you ng-scripts and ng-tests; something like the following will do (this will assist in the next step) – if the code you see is foreign to you don’t fret, any tutorial (links to some at the end of this post) will explain them later:
In /TestProject/ng-tests/MainCtrlSpec.js:
describe('Controller: MainCtrl', function() {
    beforeEach(module('MyApp'));
    var MainCtrl, scope;
    beforeEach(inject(function($controller) {
        scope = {};
        MainCtrl = $controller('MainCtrl', {
            $scope: scope
        });
    }));
    it('should have scope defined', function () {
        expect(scope).toBeDefined();
    });
});
In /ASPNETProject/ng-scripts/MainCtrl.js:
var myModule = angular.module('MyApp', []);
myModule.controller('MainCtrl', ['$scope',
 function ($scope) {
 // I'm a lonely controller :( 
 }
]);
Okay, so now we have everything in Visual Studio up ready for AngularJS. Now, on to the fun part.

Installing Karma on Windows

Now, we need to install Karma (which is used for end-to-end/integration testing). To do this, open up the DOS prompt (as an adminstrator). Browse to the base of your project directory (where both of your projects are located). Now, run the following commands:
npm install -g karma
npm install -g karma-cli
This will install Karma to your global PATH (so you can access it anywhere on the OS – such as in other projects and so forth). Now, you need to configure Karma for your project. To do so, just type in:
karma init
You’ll now be prompted to select your testing framework (Jasmine is the default), if you’d like to install Require.js (no is the default), which browser to run the tests in (Chrome is the default), the location of your scripts (see the example below – you’ll want to point them to the /ng-scripts/ and /ng-tests/ folder while selecting all Javascript files (**.js), the location/file types to exclude (empty by default), and if you’d like Karma to actively watch for changes to your files (yes!) so it can re-run them as needed. Your command line output should look like:
Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> jasmine
Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no
Do you want to capture any browsers automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
>
What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
> AngularJumpstart/ng-scripts/**.js
> AngularJumpstart.Tests/ng-tests/**.js
Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
>
Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> yes
Config file generated at "../path/to/your/project/karma.conf.js".
Note: if you don’t have valid Javascript files in the ng-scripts and ng-tests folders, you’ll get an error when trying to create the config file. Make sure you have at least an empty js file in each folder.
Now, before moving on we need to make sure that Angular is references in thekarma.conf.js file. Open it up and make sure that angular.js and angular-mock.js are included (you may need to add other files as time goes on, too). Look for the files array:
// list of files / patterns to load in the browser
    files: [
      'AngularJumpstart/Scripts/Angular/angular.js',
      'AngularJumpstart/Scripts/Angular/angular-mocks.js',
      'AngularJumpstart/ng-scripts/**.js',
      'AngularJumpstart.Tests/ng-tests/**.js'
    ],
Once you’ve saved that, all you need to do is run karma:
karma start
You’ll see the application initialize and an instance of your browser run. Every time you change any of the files that Karma is monitoring the tests will re-run (and show if they’re successful or if they fail). If you’d like to familiarize yourself with how Karma configurations work, please view the official documentation.

Wrap-Up

Well, now you have everything set up to start your AngularJS project. If you’re new to the AngularJS world, here are a few places to get started:
If you see any errors feel free to comment and I’ll take care of them. Thanks for reading!

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...