Promises With $q And Angular In Karma, Mocha & Chai
Solution 1:
When testing promises in angular, it's a best practice to depend on angular machinery to do its job to resolve promises synchronously instead of asynchronously.
This makes the code easier to read and maintain.
It's also less error prone; doing assertions in .then()
is an anti-pattern because if the callback is never called, your assertions will never run.
To use the angular way of testing, you should:
- remove
done
- do
$rootScope.$digest()
in the test to resolve promises - do your assertions
Applying this to your code would be:
describe('#addCustom', function() {
it('test', function() {
var __bool = false;
var aHack = vm.hack(true).then(function(bool) {
__bool = bool;
});
$rootScope.$digest();
expect(__bool).to.be.eq(true);
});
});
But it's tricky, because $rootScope.$digest
resolves only $q
promises, not all promises, particularly not the promises created via Promise()
constructor from various es5 shims, see this:
Promise resolved too late in angularjs jasmine test
See also:
http://brianmcd.com/2014/03/27/a-tip-for-angular-unit-tests-with-promises.html
Solution 2:
The problem is that your Promise is resolved before you setup your 'then' behavior.
Take a look at these examples that all use a setTimeout.
Post a Comment for "Promises With $q And Angular In Karma, Mocha & Chai"