Categories: AngularJS, Web Dev Training

Unit Testing in AngularJS

The modern way of development is to build and deliver web apps that include automated unit test suites. These automated tests exercise your web app to make sure that it works and doesn’t have any bugs. Tests give you the confident to say to your client or project manager or customer, yes we have the right features and yes they all work.

“Test-driven development is a set of techniques that any software engineer can follow, which encourages simple design and test suites that inspire confidence…following these two simple rules can lead us to work much more closely to our potential.

  • Write a failing automated test before you write any code.
  • Remove duplication.”

Kent Beck, Test Driven Development

Unit Tests

Unit testing is essential and of course, AngularJS lets you do some unit testing. In fact, it was built from the ground-up to co-operate with unit testing by using dependency injection.

One of the better tutorials on fully testing your AngularJS app is Full-Spectrum Testing With AngularJS and Karma.

To begin unit testing AngularJS, you need the following:

  • Karma test runner
  • Jasmine or Mocha/Chai test frameworks
  • Sinon for mocking/spies/stubs

The Karma test runner will run whatever tests you have. The Jasmine test framework lets you define tests and has assertions (such as myValue.is.expected.toBe(3)). Personally, I prefer the Mocha framework since it only defines tests, and lets you use whatever assertion library you want to use such as Chai, it also has lots of nice features.

A classic on unit testing is Test Driven Development: By Example, it’s by Kent Beck who was one of the founders of the Extreme Programming movement.

Mocking Dependencies for Integration and Unit Testing AngularJS

Sometimes when you’re writing a test, you want to make sure that your service or provider is making the right calls to another service. The way to do this is with mocks. Mocks are fake objects that keep track of which methods were called on them.

Mocks are not essential for writing tests, but there are cases where they do help. When you’re writing a controller that connects to your web app’s REST API, you want to make sure that it calls methodX and methodY. By creating a mock service and registering it with AngularJS, you can write a unit test that makes sure those two methods have been called. When using external 3rd party REST APIs, you may want to mock the $httpBackend to make sure the right calls are being made and the correct responses are returned.

Sinon is valuable for defining mocks. It lets you create method stubs and it lets you spy on method calls.

ng-modules

Find more modules on ngmodules.org

News

AngularJS Meetups

Categories: AngularJS, Web Dev Training

AngularJS Books

Today we’re covering some AngularJS books that can get you started on your path to learning how to design single-page web applications using AngularJS. While the code examples in books can sometimes become outdated, books are still valuable because they go over and explain the major concepts (directives, services, factories, unit testing, etc.) that you need when developing an AngularJS web app.

The guides on the AngularJS website are good starting points but I find that a book can go into much more detail and provide more examples that fully explore each area of the AngularJS framework. Physical books also serve as a nice break from the screen and when written well, they let you mentally figure out what the code examples will do.

“[Mastering Web Application Development with AngularJS] definitely helps a beginner and serves as a handy reference for the experienced developer. Despite having done some work on AngularJS after reading a book and online courses, this book still provided me with so much information […] that I feel I should have picked up this material first.”

— Arun Mahendrakar, 5-star review of Mastering Web Application Development with AngularJS, amazon.com

AngularJS Books

Pro AngularJS

Pro AngularJS - Apress book cover
Pro AngularJS – Apress

This book was recently published and has up-to-date code examples. It’s a heavy book and covers everything: directives, services, controllers. It has a nice dedicated section for defining AngularJS services and providers. It’s fantastic.

Here’s an excerpt from Chapter 9 – The Anatomy of an AngularJS App describing dependency injection:

“The place to start is to understand the problem DI sets out to solve. Some of the components in an AngularJS application will depend on others. In Listing 9-4, my controller needs to use the $scope component, which allows it to pass data to the view. This is an example of a dependency — my controller depends on the $scope component to perform its work.

Dependency injection simplifies the process of dealing with dependencies — known as resolving a dependency — between components. Without DI, I would have to locate $scope myself somehow, probably using global variables. It would work, but it wouldn’t be as simple as the AngularJS technique.

A component in an AngularJS application declares its dependencies by defining arguments on its factory function whose names match the components it depends on.”

As you can see, the explanation is quite clear, perfect for anyone new to AngularJS.

Buy Pro AngularJS now

Mastering Web Application Development with AngularJS

Mastering Web Application Development with AngularJS - Packt Publishing book cover
Mastering Web Application Development with AngularJS

This book gives a great overview and walkthrough of major concepts. One thing that’s impressive is that the book has unit tests for every example. Write out the code, write the unit test and run it and you can see exactly what’s going to happen.

You can click here to see an excerpt of Chapter 5 – Creating Advanced Forms.

What I really like about this book, aside from the extensive unit tests/examples, are the easy to understand explanations of core AngularJS concepts. For example, the $digest cycle and when you need to use the $apply method on scopes. If you understand them, you can improve the performance of your web app and you can avoid common mistakes.

Here’s an excerpt from Chapter 11 – Writing Robust AngularJS Web Applications, page 294:

“The idea behind AngularJS model-changes tracking mechanism is based on the observation that at the end of the day, there is a finte (and rather small) number of situations where models can change. Those include:

  • DOM events (user changing value of an input field, clicking on a button to invoke a JavaScript function and so on)
  • XHR responses firing callbacks
  • Browser’s location changes
  • Timers (setTimeout, setInterval) firing the callbacks

Indeed if none of the earlier events take place (user is not interacting with a page, no XHR calls have finished, no timers firing) there is no point in monitoring the model for changes. There is simply nothing going on for a given page, the model isn’t changing, so there is no reason to re-render the DOM.

AngularJS starts its model-observing machinery if and only if it is explicitly told to do so. To bring this sophisticated mechanism to life, we need to execute the $apply method on a scope object.”

As you can see, the explanation is clear and the book is full of gems like this.
Buy Mastering Web Application Development with AngularJS now

AngularJS (O’Reilly)

AngularJS - O'Reilly book cover
AngularJS – O’Reilly

Here’s an example of a good book that has outdated code examples. I would recommend getting this as a reference. This book is a solid reference that explains the major concepts so that you can apply them on your own.

You can click here to download a free sampler of O’Reilly AngularJS – Chapter 1.

I hope that they release a 2nd edition of the book with updated examples because O’Reilly books are usually pretty good.

Buy it now

Other AngularJS Books…

ng-modules

  • ux-datagrid: a highly performant list and data grid, designed for mobile devices.
  • restangular: service that makes creating proper REST APIs easy.
  • angular-translate: add multiple languages and translation to your app.
  • angularfire: use this library to interact with your Firebase backend database.

Find more modules on ngmodules.org

News

  • AngularJS support in PhpStorm: autocomplete, custom directives, refactoring, routing and URL template support are now in JetBrains’ wonderful IDE, PhpStorm.
  • AngularJS 2.0: implementation of the next major version is beginning, mobile-first and using ES6 (ECMAScript 6). More modularity is planned and a less complex dependency injection system is being designed.

AngularJS Meetups

Categories: AngularJS, Software Development, Web Dev Training

AngularJS: testing services that use $resource

In this article we discuss one aspect of AngularJS testing, namely how to unit test code that uses $resource.

When working on a project that uses ngResource (imported into the code as $resource), the unit tests related to the service relying on $resource were failing. I jumped in to do a rewrite or to scrap them entirely if necessary.

  1. The Problem: how to test a service that relies on $resource
  2. Unit Tests Vs. Integration Tests
  3. The Solution: break the dependency and test each part separately

Continue reading “AngularJS: testing services that use $resource”

Using Sequelize with Promises (with and without Q)

Using Sequelize with Promises (with and without Q)

Here is a basic example of using Sequelize with promises using the Q Promises library.

https://gist.github.com/omouse/9401609

Q is basically a way for you to use Promises in Node.js. You can use it with Sequelize to make it easier to perform the SQL operations through the library.

Categories: AngularJS, Web Dev Training

A Primer on AngularJS Services

The article is by Michael Herman it’s a very nice short article on how to use AngularJS services.

The article talks about what a service is and how to create one. It’s very well done and the code is easy to follow and understand.

When you’re first starting with AngularJS it can be tempting to put a lot of functionality into a controller, but you should be separating concerns and moving some of that functionality into separate services that the controller uses. Even for small apps, it’s good to get into the habit of creating separate services.

As Michael says,

“If your controller is handling more than just defining the scope or initial state of your app, connecting your models and views, then it’s are probably doing too much.”

The article is a prime example of great documentation of a core AngularJS feature.

Read the article

See a demo of the code in action.

Hope this article helps you a lot on your journey to become an AngularJS master!

Disable CSRF Verification in Django Class-Based View

While working on a Django web app, I had to disable CSRF protection in a view. The goal was that our API was accepting data from another part of our website and we needed to skip the CSRF protection just for that one page.

There are two great answers on how to do this on StackOverflow:

  1. How to disable Django’s CSRF validation?
  2. How can I disable Django’s CSRF protection only in certain cases?

And nice documentation for Django Rest Framework on disabling CSRF for AJAX calls.

The answer is basically to use the csrf_exempt as a function that wraps the class-based view’s .as_view call and to do this in the urls.py routing file.

For example,

HelloView.as_view()

will become

csrf_exempt(HelloView.as_view())
Categories: AngularJS, Portfolio, Software Development, Web Dev Training

Deconstructing AngularJS Injector

I was reading through Coders at Work and realized that I haven’t done much code reading lately, other than reading through code samples in tutorials and articles. The interviews in the book suggested that code reviews and code reading are one of the most important things you can do as a professional programmer. This gave me the idea to write this article on the Angular injector.

I’ve been doing some stuff with AngularJS and one of the key ideas is dependency injection. Here’s a deconstruction of Angular injector.js which contains all the functions and classes for dependency injection.

Continue reading “Deconstructing AngularJS Injector”

Categories: Web Dev Training

Django: dumping and loading databases

At work , we have this situation where we want to dump the database from the production servers so that we can work with that data on our local development machines. As part of an internal app (which another developer is working on open-sourcing parts of, UPDATE: the app is on github, however I no longer use it myself, not sure if it’s still used internally at Trapeze), we have two management commands to help us with this: load_devdata and dump_devdata.

The reason we use a management command is because we don’t install Fabric on our production servers to run these commands, we don’t use shell scripts either.

The database commands are PostgreSQL-specific and we use rsync to copy the media files.
Continue reading “Django: dumping and loading databases”

Django filter versus get for single object?

Django get versus filter for single object?

While working on a project, we use a particular pattern in Django for getting a single object. We first filter the queryset by the id or slug and then check if the queryset exists. If so, then we return the object otherwise we return none.

Here is an example of how this looks in Python:

models = MyModel.objects.filter(id=24)
if len(models) > 0:
  return models[0]
else:
  return 'could not find model'

Which brings us to the question of get versus filter, which one should we use? Should we lean towards checking the number of objects from the queryset filtering or rely on the get and handle/catch any exception thrown when no object is found?

According to James Bennet, Django release manager and author of django-registration, this isn’t necessary,

get() is provided specifically for this case. Use it.

Option 2 is almost precisely how the get() method is actually implemented in Django, so there should be no “performance” difference (and the fact that you’re thinking about it indicates you’re violating one of the cardinal rules of programming, namely trying to optimize code before it’s even been written and profiled — until you have the code and can run it, you don’t know how it will perform, and trying to optimize before then is a path of pain).

The reason we avoid it is because the get() method requires that we use a try/except block and I rarely see exceptions being caught in our code. Jeff Knupp suggests that writing Python with exception handling leads to cleaner code.

Let’s take a look at that example. If we use the get() method to retrieve a model instance and use exceptions to catch the case where the object could not be found

try:
  model = MyModel.get(id=24)
  return model
except MyModel.DoesNotExist:
  raise

You’ll notice how we’re using the bare “raise” statement in the example in line 5. This will let you propagate the traceback and original exception up the chain. This means you do not have to invent new types of exceptions.

In his article, Jeff Knupp walks through the performance characteristics of using exceptions and finds that the trade-off in speed is acceptable, something on the order of thousandths of a millisecond. So there’s no way to use speed as an excuse to avoid exceptions!

Start using exceptions in Python and use the get() function of querysets whenever you want to find exactly one model instance.

UPDATE: Some good books on Django design patterns and coding style:

Categories: Web Dev Training

Django File Uploads: Validating File uploads in Django 1.0

While working on Clapton, the Django-based Content Management System (CMS), I had to write validation code for file uploads. This is needed because Clapton contains applications specific to media types such as documents which requires Word Documents, PDFs or OpenDocumentFormat files, and podcasts which requires MP3 or OGG files. But how do you guarantee that the right files are uploaded? By using Django’s custom fields and newforms module.

The following code creates a DocumentField class that only accepts Word, Text, RTFs, HTML, PDF or ODF files:

https://gist.github.com/omouse/5942532

When a DocumentField object is used in a custom form and the form is being validated, the clean method is called.

First, it calls the FileField‘s clean method which validates the field using the FileField validation criteria. Then it constructs two tuples file_types and file_exts containing the valid content-types and the valid file extensions. The data argument is check against the content-types, which are taken from the IANA MIME Media Types page (content-type information for files is sent along with any HTTP file upload).

Quite simple. To turn this into an image validator for PNG files, change the file_exts to ('image/png') and file_types to ('.png').

Just toss that code into your application views.py file, create a custom form and insert the field and that’s it.

Click here for more information on the Django Forms API.

Interested In Other Django Topics? Check This Out