Correct moment to call $rootScope's $apply/$digest method in a test

123 Views Asked by At

Angular testing docs shows an test sample where $apply is called before testing assertions. I tried to do the same but my test is not working properly. The first code that should break, works... it seems that my assertion is not running. The second code, my test works but it's different from the documentation (which I like the style better).

First:

it('tests angular promises', function() {
    getABC = function() {
        return $q((resolve, reject) => {
            resolve('abc');
        });
    };

    var state = getABC()

    $rootScope.$apply()
    // assertions come after $apply call as in documentation: doesn't work.
    state.should.eventually.be.equal('abcc') 
})

------
✓ tests angular promises


1 passing (78ms)

Second

it('tests angular promises', function() {
    getABC = function() {
        return $q((resolve, reject) => {
            resolve('abc');
        });
    };

    var state = getABC()

    state.should.eventually.be.equal('abcc')
    // assertions come before  $apply call: works
    $rootScope.$apply()
})

------
1 failing

1) tests angular promises:

  AssertionError: expected 'abc' to equal 'abcc'
  + expected - actual

  -abc
  +abcc
1

There are 1 best solutions below

0
On BEST ANSWER

The shown example is a different case.

It uses

expect(resolvedValue).toEqual(123);

assertion that doesn't involve promises.

On the other hand,

state.should.eventually.be.equal('abcc')

uses chai-as-promised for assertion. It chains state with then under the hood to get the value and assert it. And $q promise chains are executed only on digest. That's why $rootScope.$digest() is necessary after eventually assertions.

See also this answer for more details on how to test Angular with chai-as-promised.