javascript - Unable to test .success function within controller -
i have simple controller , service performs http post. controller has .success , .error callbacks trying write unit tests:
to call btnclick:
<button ng-click="btnclick('cart')">click</button> controller:
app.controller('mycontroller', function($scope, myservice, $timeout) { $scope.btnclick = function (action) { $scope.postdata = {"id": $scope.myid, "user": $scope.myuser}; $scope.cartrequest = function() { $scope.disabled = true; $scope.mytext = ''; myservice.postaction('cart', $scope.postdata) .success(function (data, status, headers, config) { $timeout(function(){ $scope.disabled = false; $scope.mytext = 'inside timeout'; $timeout(function(){ $scope.hidebtn = true; }, 1400); }, 1500); }) .error(function (data, status, headers, config) { $scope.carterror(); }); }; switch(action) { case "cart": $scope.cartrequest(); break; } }; myservice:
app.factory('myservice', function ($http) { return { postaction: function(uri, postdata) { return $http({ method: 'post', url: '/cartinfo/' + uri, data: postdata, headers: {'content-type': 'application/json'} }); } }; }); }); my test:
describe('cart api: can cart details', function () { var myservice, httpbackend; var customerinfo = { "accountid" : "12345678901", "username" : "mytestuser", "firstname" : "joe", "lastname" : "bloggs" }; beforeeach(inject(function($rootscope, $controller) { scope = $rootscope.$new(); ctrl = $controller('mycontroller', {$scope:scope}); spyon(scope, 'btnclick').and.callthrough(); inject(function ($httpbackend, _myservice_, $timeout) { myservice = _myservice_; httpbackend = $httpbackend; timeout = $timeout; }); })); it('should check if user logged in', function () { scope.customer = customerinfo; scope.btnclick('cart'); var returndata = {}; var result = {}; var mockdata = { "accountid" : scope.customer.accountid, "username" : scope.customer.username}; httpbackend.expectpost('/cartinfo/cart', mockdata, function () { return { 'content-type': 'application/json' }; }).respond(200, returndata); myservice.postaction('unlock', mockdata).success(function (response) { console.log("hello"); timeout.flush(1501); scope.$apply(); expect(scope.disabled).tobefalsy(); expect(scope.mytext).toequal('inside timeout'); }); }); }); it seems though .success block within test never called 2 expects:
expect(scope.disabled).tobefalsy(); expect(scope.mytext).toequal('inside timeout'); dont seem run.
promises in specs assume specs should asynchronous. angular promises have tested synchronously:
myservice.postaction('unlock', mockdata); $rootscope.$digest(); timeout.flush(); // can omitted if scope watchers don't affect spec // scope.$apply(); expect(scope.disabled).tobefalsy(); expect(scope.mytext).toequal('inside timeout');
Comments
Post a Comment