0

I'm testing a promise with angularjs jasmine, and sinonjs. I'm puzzled by something regarding promises. Here is my code:

it('should return data with length 4 ', inject(function ($rootScope) {              
  var storageData;

  mockDualStorage.getData.returns($.when(''));
  // mockDualStorage.getData is called by getStorageData

  // $rootScope.$digest() // not working here

  dataGetter.getStorageData().then(function (data) {
    console.log(1);
    storageData = data;
  });

  $rootScope.$digest(); // only working here

  console.log(2);
  expect(storageData.length).toBe(4)// ok

  }));

Couple of things are strange here.

If I put $rootScope.$digest() above the dataGetter.getStorageData() then function is never executed.

  • When the $rootScope.$digest() is below, then gets executed, and order of console.log is 1,2

  • Why won't then execute when $rootScope.$digest() is above? As I understand promise is already resolved?

Ivan V.
  • 7,593
  • 2
  • 36
  • 53
  • I suspect the `then` callback isn't properly closed with a `})` in your answer. Can you fix? Also, can you expand the example a bit, showing the surrounding/earlier function, where `$rootScope` is injected? It seems strange the `$rootScope` is defined when it's not in a `beforeEach`, `it` or `afterEach` block. – Michal Charemza Apr 20 '14 at 08:03
  • Everything is properly closed and injected in to the test. My question is why is the promise working only **after** I register `then` callback? According to promise specification attaching `then` to a resolved promise should be immediately executed. – Ivan V. Apr 22 '14 at 12:26
  • I've edited the question to tidy up the placement of `})`, as it looked like they closed the function defined on the top line, and not the `then` callback. (If I've misunderstood, of course feel free to change it) – Michal Charemza Apr 22 '14 at 13:02

1 Answers1

0

After more carefully reading the documentation, found the answer right there.

Differences between Kris Kowal's Q and $q : There are two main differences: $q is integrated with the $rootScope.Scope Scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI.

AngularJS $q service documentation

Graham
  • 7,431
  • 18
  • 59
  • 84
Ivan V.
  • 7,593
  • 2
  • 36
  • 53