Angular.js: It's not obvious that tests with promises must call $rootScope.$apply()

Created on 29 Jan 2013  路  8Comments  路  Source: angular/angular.js

I just spent a few hours pulling my hair out because my tests weren't passing and I couldn't figure out why. It turns out it's because $q's promises don't actually get resolved during tests unless you call $rootScope.$apply. (This appears to have been masked in my earlier testing because I was testing services that used $timeout and $httpBackend and their flush methods.)

Please make sure to document this behavior when you improve the testing documentation.

All 8 comments

@inklesspen, actually it is in the example test on this page: http://docs.angularjs.org/api/ng.$q

Would be willing sending a pull request with the proposal of additional explanations you would like to see?

Yeah, and that's where I finally found it; I'd been expecting to find it in documentation such as http://docs.angularjs.org/guide/dev_guide.unit-testing or http://docs.angularjs.org/guide/dev_guide.services.testing_services

@inklesspen, going to close this for now since it is documented. Would be awesome if you could send a pull request with proposed improvements.

So requests to improve the documentation are unwelcome unless I give you a pull request? Good to know.

@inklesspen they are highly welcomed! It is just that it is documented already but not in the place you were expecting it... so suggested to send a PR with your proposal. Not sure how to action on this one otherwise...

:+1:, I just burned a few hours banging my head against this exact problem until I found this github issue. The reason it's so confusing is that I'm not doing anything with $scope in my code or in my tests at all. I thought that I would only have to call $rootScope.$apply() if I wanted the scope to update.

+1

:+1: also burned a few hours searching for the solution.

Was this page helpful?
0 / 5 - 0 ratings