vendredi 26 décembre 2014

Unit test a service which returns ngResource in angularjs with mocha, chai and sinon

I have a service which returns $resource as like below



myApp.factory('myService', ['$resource', function($resource){
return $resource('/myapi/:id', {id:'@_id'},
{
update:{
method:'PUT',
url:'myapi/update/url/:myId'
}
}
}]);


and the controller which uses the service as like below



myApp.controller('myController', ['$scope', 'myService', '$state', function($scope, myService, $state){

$scope.isCallbackCalled = false;

$scope.update = function() {
return myService.update({myId:'4345'},
function(response){
// Couldn't able to test this success callback in mocha and sinon
$scope.isCallbackCalled = true;
$state.go('success');
}).$promise;
};
});


and my unit test case as like below



describe('myController', function() {
var myService,
updateDefered,
updateSpy,
scope,
myController,
stateSpy;

beforeEach(inject(function($controllers, $rootScope, $state, myService, $q) {
scope = $rootScope.$new();
updateDefered = $q.defer();
updateSpy = sinon.stub().returns(updateDefered.$promise);
stateSpy = sinon.stub();
myService = {
update:updateSpy
};

myController = $controller('myController', {
$scope:scope,
myService:myService,
$state:{
go:stateSpy
}
});

updateDefered.resolve();
}));

it('should call scope.update() method and then update service', inject(function($rootScope, $httpBackend) {
$httpBackend.whenPUT('/myapi/update/url/:myId').respond({});
$rootScope.$apply();

scope.update();
$httpBackend.flush();
// here it always fails, and I couldn't able to test the $resources
// internal success callback
expect(scope.isCallbackCalled).to.be.true;
stateSpy.should.have.been.calledOnce;
});
});


Here I couldn't able to unit test the isCallbackCalled when calling the $resource's update method with success callback. If I use as like below instead of internal success callback, i can able to unit test isCallbackCalled



$scope.update = function() {
return myService.update({myId:'4345'}
// instead of internal success callback now I am using then method of promise
//function(response){
// Couldn't able to test this success callback in mocha and sinon
// $scope.isCallbackCalled = true;
// $state.go('success');
//}
).then(function(response){
$scope.isCallbackCalled = true;
$state.go('success');
});
};


So, How do I unit test when the resource method calling has internal success callback (whether it is called or not and changed the scope variabales) or how do I check whether or not stateSpy has been called?


Aucun commentaire:

Enregistrer un commentaire