Showing posts with label promise. Show all posts
Showing posts with label promise. Show all posts

Saturday, February 8, 2014

Mocking Promise Objects within AngularJS

Assumption: You understand the value of breaking up your application into modules.  Too many: one module per service/controller, Too few: one module for entire application, assuming your application is not a basic TODO. Long story short: with modules, you can reduce the scope of your test without having to include the full application with each test.

Background: We’ve been using AngularJS to help with our new order entry system and it’s working great.  Testability is at the forefront of angular’s offering and we attempt to have as much valuable code coverage as we can within our application.  Early on, we encountered an obstacle while trying to test $q within a controller’s init function.

Obstacle:  One of our controllers has to init with a promise object and several of the scope objects within the controller depend on the resolution of the promise.

Controller to test


  • you can see we have a client module
  • product module is an external dependency, we don’t want to bring that module into our test
  • the product service returns a promise object, most likely $q since we’re using AngularJS

Test with mocked promise object



  • when we first encountered this problem, we were forgetting we were JavaScript developers…it’s easy to get caught up in the JS library itself and expect the library to solve all of your problems for you…can we use $httpBackend here? no…what if your promise isn’t really even working with http?  what if it is but you don’t want to test the http call since that (module) is out of scope for this test?…why doesn’t ng do something for us - who cares…JS is easy enough without ng!
  • since JS is one of the easiest languages to mock (if not the easiest), just create an object in your beforeEach to resemble the promise you require
  • you can see we mock the entire productService & testing the productService itself should be out of scope here
  • our test is really simple but it proves the concept for mocking promises