Showing posts with label angular. Show all posts
Showing posts with label angular. Show all posts

23 September 2013

Using $q promises to run synchronous code asynchronously

The Q Javascript library provides a great way to handle the results of asynchronous tasks in a simple flexible manner. But the APIs required to actually generate and return promises for your own synchronous code are often a bit verbose, particularly if you want to catch and pass on exceptions as well.

Here's a convenient shortcut: Just call $q.when() with no arguments, then place all of your synchronous code (that you want to behave asynchronously) in a subsequent .then() call. This will automatically pick up any results, or exceptions, and pass them on as promises.

E.g.
function myAsyncSqrt(value) {

  return $q.when()
    .then(function() {
      return Math.sqrt(value);
    });
}
...
var promise = myAsyncSqrt(16);
promise.then(
  function(res) { alert('answer:' + res); },
  function(err) { alert('uh oh:' + err); });

19 August 2013

How to mock an Angular service for testing

To inject a fake version of myService, and intercept calls to myMethod, do something like this:

Or check out the cool video here.

    var myMethodFake = function() { ... };

    beforeEach(function () {
        module(function ($provide) {
            mockMyService = {
                myMethod: jasmine.createSpy('myMethod').andCallFake(myMethodFake)
            };
            $provide.value('myService', mockMyService);
        });
    });

    it('does stuff', inject(function(myService) {
       myService.myMethod();
    });