user1707075 user1707075 - 3 months ago 74x
AngularJS Question

Angular $q promise Unit testing using Mocha, Chai, Sinon

I'm trying to get my simple angualr $q promise unit test to work. But I've been having problems getting it to work.
Here's my angular file.

app.controller('theCtrl', ['$scope', '$q', function($scope, $q) {
$scope.addOne = function(num) {
var q = $q.defer();
if(angular.isNumber(num)) {
} else {
return q.promise;

$scope.myVal = 0;
$scope.promise = $scope.addOne($scope.myVal);

// $scope.promise.then(function(v) {$scope.myVal = v }, function(err) {$scope.myVal = err});


I'm using Mocha, Chai and sinon for the unit testing.
Here's my test file.

describe("Contacts App", function() {
describe("the contact service", function(){
var $scope, theCtrl, $q;


beforeEach(inject(function($injector) {
var $rootScope = $injector.get('$rootScope');
var $controller = $injector.get('$controller');
$scope = $rootScope.$new();
theCtrl = $controller('theCtrl', {$scope: $scope} );
$q = $injector.get('$q');


it('should have a properly working promise', function() {
// Any answers?

Any suggestion would be really appreciated. Thanks, Cheers!


First proposition

You can use mocha's callback function to test asynchronous code along with the angular $timeout.flush()

it('should have a properly working promise', function(done) {
   $scope.promise.then(function() {

Second proposition (recommended by Mocha)

You can use and return a promise. Your code should look as below

it('should increment the input if number given', function() {
   return $scope.addOne(1).should.eventually.equal(2);