Showing posts with label testing. Show all posts
Showing posts with label testing. Show all posts

21 January 2015

Using ES6 with your AngularJS project

Earlier this month Glen Maddern (aka. The <x-gif> guy) posted an article, Javascript in 2015, with a YouTube video giving "A brief tour of JSPM, SystemJS & ES6 features".
If you haven't seen it already, go take a look.

In a short time he has a front-end application written in ES6 running, with modules being loaded and transpiled (via Traceur) by SystemJS.  And at the end he creates a self-executing, minified bundle of that application code, including source maps.

These tools make it easy to start using ES6 now with your existing AngularJS applications - which will almost certainly be step 1 on the migration plan to Angular v2.0. Even without that, the goodies from ES6 are too good to pass up.

As a demonstration, we're going to take angular-seed, update it to ES6 using SystemJS, bundle the app for production with systemjs-builder, and configure Karma to run unit tests using the karma-systemjs plugin.

SystemJS Setup

OK - lets get started.
We're going to clone an angular-seed repo, switch to a new es6 branch, then install dependencies from npm and bower. The dependencies for angular-seed are a bit old, so we've updated them too:

git clone https://github.com/angular/angular-seed.git
cd angular-seed
git checkout -b es6
npm install --save-dev systemjs-builder karma-systemjs karma#~0.12 karma-chrome-launcher karma-firefox-launcher karma-jasmine
bower install -f -S angular#1.3.x angular-route#1.3.x angular-mocks#~1.3.x system.js

Next thing we need is a config file for SystemJS: `app/system.config.js`. This is where we tell SystemJS how to find certain modules.  In this case, we're going to map the module names 'angular' and 'angular-route' to their long paths:

Next we'll change `app/index-async.html` to use SystemJS rather than angular-loader:

Last thing to do is add `import` statements to `app/app.js` to include the rest of the application, as it's what will be loaded by `System.import('app')`:

Now if you load up `app/index-async.html` using a local webserver (The one included with angular-seed start with `npm start`) you should see the angular-seed application running as normal, only it's been loaded as a set of ES6 files.

This is just the bare minimum required to get existing code to ES6 using SystemJS.
You can add more ES6 syntax and rearrange the modules as you like.

Here's my suggestions:

  • Use classes for Controllers (Controller as), Services (.service()), and Providers
  • Use ES6 modules over angular modules
  • Use arrow functions - cause they're sugary sweet!

Bundling for Production

With our SystemJS config file already in place, we only need to pass that into systemjs-builder with a slight tweak to bundle our code for production. This is a simple node script you can run with `node bundle.js` that will bundle all the modules imported by `app/app.js` and output the result to `app/bundle.js`:

And finally we change `app/index.html` to include `traceur-runtime.js` and the `bundle.js` file we just created:

Unit Testing

Karma works like most a typical browser application: Load all <script/> tags, then start the application `onload`. In this case, we want Karma to let SystemJS handle loading everything, then start the test runner once everything is ready.  This is essentially what karma-systemjs does for us.

First we need to adjust `karma.conf.js`:

Next we update our test suites to act like ES6 modules - importing the code to be tested, along with any dependency libraries.

Note how `module()` has been changed to `angular.mock.module()`.

And that's it.
An existing AngularJS project converted over to using ES6 with SystemJS, with working unit tests and a means of generating bundles for production.
You can find the complete code here: https://github.com/rolaveric/angular-seed/tree/es6

Cheers,
Jason Stone

16 May 2014

E2E testing AngularJS with Protractor

In the beginning, there was JSTestDriver.
It was a dark time, with much wailing and gnashing of teeth.

Then came Testacular: The spectacular test runner.
For a time, once everyone stopped sniggering like teenagers, it was good.
Unit tests ran quick as lightning on any browser that could call a web page.

Finally, to please the squeamish who were too embarrassed to speak of Testacular to colleagues and managers, the creator moved heaven and earth to rename it Karma.
And it was, and still is, good.

But there was still unrest.
While unit tests were as quick as the wind, E2E (end-to-end) tests were constrained from within the Javascript VM.
"Free me from this reverse proxy! Treat me as though I were a real user!"
And thus Protractor was born.

*ahem*
Protractor is the official E2E testing framework for AngularJS applications, working as a wrapper around Web Driver (ie. Selenium 2.0) which is a well established and widely used platform for writing functional test for web applications.  What makes it different from Karma is that Karma acts as a reverse proxy in front of your live AngularJS code, while Web Driver accesses the browser directly. So your tests become more authentic in regards to the user's experience.

One cool thing about Web Driver, which I didn't realise till recently, is that it's API is currently being drafted up as a W3 standard.  We're also seeing a number of services appear for running your selenium tests using their VMs, which is useful for doing CI and performance testing without taking on the operational overhead yourself.

Let's go!

The App

I've created a simple application to write tests for.  So first we'll clone the application from github, install the local NodeJS modules, and then install the required bower components:

git clone https://github.com/rolaveric/protractorDemo
cd protractorDemo
npm install
node node_modules/bower/bin/bower install

Now you should have a copy of the application with node modules 'bower' and 'protractor' installed, and AngularJS installed as a bower component.

The application is dead simple.  It has a button with the label "Click to reverse".  When you click it, it (you guessed it) reverses the label. So our tests should look something like this:
  • Load App
  • Click button
  • Assert that label is now reversed
  • Click button again
  • Assert that label is now back to normal

Installing Selenium

Protractor comes with a utility program for installing and managing a selenium server locally: webdriver-manager
Calling it with "update" will download a copy of the selenium standalone server to run.

node node_modules/protractor/bin/webdriver-manager update

Setting up for tests

First thing we need is a configuration file for protractor.  It tells protractor everything it needs to know to run your tests:  Where to find or how to start Selenium, where to find the web application, and where to find the tests.

Since we're using webdriver-manager to run selenium server, we'll tell it the default address to find it: http://localhost:4444/wd/hub
Optionally you could give it the location of the selenium server JAR file to start itself, or a set of credentials to use SauceLabs.

The tests we'll place in "test/e2e", and npm start spins up a local web server at "http://localhost:8000/".  So the basic configuration file stored in "config/protractor.conf.js" looks like this:

exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['../test/e2e/*.js'],
baseUrl: 'http://localhost:8000/'
};

There's actually a lot more you can do with the configuration file, but this is all we need to get going. Check out the reference config in protractor's github for more options.  You can do things like pass parameters to selenium, your testing framework, and even to your tests (eg. login details).

Writing tests

In "test/e2e/click.js" is a simple test for the "Click to reverse" behaviour:

The process behind writing E2E tests is pretty simple: Perform an action, get some data, then test that data.  Generally each action or query also involves finding a particular element on the page, either by CSS selector, ng-model name, or template binding.

First it opens the "index.html" file (which it finds relative to the baseUrl in the configuration file), finds the button by it's binding, clicks the button, then gets the button's text value and tests it.  Then we click the button again, get it's text value, and test that it's changed back to normal.

Running tests


Now for the payoff - the running of the tests.

First we'll start up the web and webdriver servers:

npm start
node node_modules/protractor/bin/webdriver-manager start

Then we tell protractor to run the tests according to our configuration file:

node node_modules/protractor/bin/protractor config/protractor.conf.js

If everything's gone well, you should soon be rewarded with the following result:

Finished in 2.061 seconds
2 tests, 2 assertions, 0 failures

And there you have it.  Webdriver tests for your AngularJS application with minimum pain.  If you already have angular-scenario based tests, converting them to Protractor should be a trivial "search & replace" exercise with the right regular expressions.

5 February 2014

Unit Testing AngularJS

It's not always obvious how to write automated tests for the different components in AngularJS, so I'd like to share some of my techniques for testing AngularJS applications.

Automated Testing Stack

If you've got absolutely no automated testing setup at all, then I recommend looking at using one of the following to give you some scaffolding: angular-seed, Yeoman, or ng-boilerplate.

Here's a quick overview of each piece of the unit testing stack.

Karma: The Test Runner

Karma does the work of starting our browser(s), running the tests, and reporting the results in whatever format we desire.  It can also handle pre-processing code for doing things like compiling CoffeeScript or injecting Code Coverage markers.

Jasmine: The Test Framework

We need a format to write our tests in.  The default one used by the AngularJS community, and what I'll be writing the rest of this article with, is Jasmine.  It uses a BDD (Behaviour Driven Development) style, which essentially means it tries to make your tests read like business specifications that an analyst could understand.
Here's a quick example of a Jasmine test:


The "describe()" method is used to group tests.  The "it()" method is the specification: a descriptive string for the spec, and a function for testing that spec.  The "expect(value).toSomething()" is an assertion.  You pass a value to "expect()" and then you run what's called a 'matcher' method against it.  You can also run setup and teardown code using "beforeEach()" and "afterEach()" methods.
Karma has an adapter for interpreting the results from Jasmine, which it can then feed into various reporters.  So if Jasmine isn't your poison, chances are there's an adapter out there for whatever testing framework you prefer.

ng-mocks: The Helper Library

If you've ever downloaded AngularJS as an archive, you may have spotted the angular-mocks.js file.  This contains the ngMock module, which provides a set of helper functions to make your testing life easier.  Particular the inject() method which you can pass a function with injectable parameters (eg. Services), and it will handle all the dependency injection for you.

Services

Alright.  Down to the actual testing.
I'm going to start with the simplest example.  This will work for anything produced with "module.value()", "module.constant()", "module.factory()", or "module.service()".


The relevant parts for AngularJS developers is "module()" and "inject()".

The best way to think of the "module()" function is that it's doing the same job as the "ng-app" directive - it bootstraps that module so you can inject it's components.  The great thing is that the scope for that module only lasts for a single test.  So changes you make in one test won't have an effect on the next test.

The "inject()" method hooks into Angular's dependency injector.  So you can pass it a function with your dependencies, and it will handle their injection for you.  Although it won't work if the module those components belong to has not been loaded yet by "module()".

Here's a more verbose example; a pattern which I often use myself:


Handling Dependencies

I try not to make any function calls in my service constructor.  This makes things simpler if, for example, I depend upon another service which I want to mock during testing (It is called "unit" testing for a reason).  Lets say "myService.myMethod()" called "anotherService.anotherMethod()".  Rather than test what "anotherMethod()" does within the test for "myMethod()", I just want to confirm that it gets called.  I can do this by getting an instance of "anotherService", using "inject()", and replace "anotherMethod()" with a spy which tracks if and how it gets called:


If "myService" was using a method from "anotherService" in it's constructor, that would make things trickier, but not impossible, to test.  Services are constructed only when they're first injected (no point constructing something that's not even being used).  So the trick is to inject "anotherService" first, set up your spy, then inject "myService".


You couldn't do this if your constructor was calling one of it's own methods (eg. "myService.init()").  So when you're writing a complex constructor for a service, or controller, you really need to sit back and think "How am I going to test this?".

Filters

Filters are just functions.  The key to testing them is to get yourself a reference to those functions.  This is simple with "inject()".  You should set a parameter with the name of your filter with the suffix "Filter".  Here's an example:


Alternatively you can use the "$filter()" function, like so:


Controllers

Now we're getting somewhere interesting.  Controllers are different to services in that their dependencies aren't just services - they can be "resolve" values, such as "$scope".  On top of that, not all controllers just attach properties to "$scope".  Some will attach properties to themselves through "this".  2 examples are using controllers for directive to directive communication, and the new 'ng-controller="MyCtrl as scope"' optional syntax for controllers being introduced in AngularJS v1.2

So we need a way to inject specific dependencies into our controller, and then we (may) need a reference to the instance of that controller function.  The way to achieve this is to use the $controller service:


That works if you're not doing much with the $scope except for attaching properties.  But what if I'm using some of the built in functionality for scopes like "$watch", "$on()", "$broadcast()", or  "$emit()"?  You could create spies to mock all these things.  I personally like to use a real $scope object.  So how do I get one?  Inject "$rootScope" and call "$new()" on it:


Here's my template for controller tests:


Directives

The key to testing directives is to use the $compile service to compile a DOM element which includes your directive.  $compile will trigger your directive's code, and you can then start querying the DOM element and scope to test it's behaviour.
Here's a simplified version of the ng-hide directive (Similar to the original, but without $animate support):


To test it, we need to compile the directive, and then test how the element reacts when we change the scope or trigger use actions.
Here's a test taken straight from the AngularJS source code (The best source for writing and testing directives):


Walking through it, first it uses jqLite/jQuery to create a DOM element with the directive.
Then it passes the element to the $compile service, along with a scope object (in this case $rootScope), which runs the code for any directives it finds.
Then it tests that the element is still visible, since "exp" is undefined and therefore falsy.
Then it sets "exp" to "true", triggers the digest loop so that the $watch gets run, and then tests that the element is now hidden.

Most of your directive tests are going to follow this pattern some how:
  1. Create a DOM element with your directive.
  2. Pass it to $compile(), along with a scope object.
  3. Change the scope.
  4. Query the DOM for changes.

Providers

A provider is really no different from a service, except that it requires a special "$get()" method for "providing" the dependency, and it can exist during the "config" phase of AngularJS' lifecycle.
The trick is getting a reference to the provider in pristine condition (ie. Before "$get()" is called).  The way you do this is using the "module()" helper function, provided by ng-mocks:

In this scenario we have a provider called "myServiceProvider", which belongs to module "myModule".
We use the "module()" function to instantiate "myModule", and then get a reference to "myServiceProvider".
However, calling "module()" alone is not enough.  It doesn't actually do anything until "inject()" is called.  So we just call "inject()" with no dependencies, meaning "myServiceProvider.$get()" has still not been called.

Conclusion

AngularJS has been built from the ground up with testing in mind, but it's not always immediately obvious to new comers as to how they might test a particular component.
But once you know the trick, the pattern to adopt and the services to call, there's nothing to stop you writing a suite of tests you can rely on.
Then library upgrades become a trivial matter of: drop in the new version, run the tests, and fix any failures.  I couldn't use the weekly AngularJS builds without it.