Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  138] [ 7]  / answers: 1 / hits: 20565  / 10 Years ago, wed, may 14, 2014, 12:00:00

This is a controller with a submit function:



$scope.submit = function(){   

$http.post('/api/project', $scope.project)
.success(function(data, status){
$modalInstance.dismiss(true);
})
.error(function(data){
console.log(data);
})
}
}


This is my test



it('should make a post to /api/project on submit and close the modal on success', function() {
scope.submit();

$httpBackend.expectPOST('/api/project').respond(200, 'test');

$httpBackend.flush();

expect(modalInstance.dismiss).toHaveBeenCalledWith(true);
});


The error I get is:



Error: Unexpected request: GET views/appBar.html


views/appBar.html is my templateUrl:



 .state('project', {
url: '/',
templateUrl:'views/appBar.html',
controller: 'ProjectsCtrl'
})


So somehow ui-router is making my $httpBackend point to this instead of my submit function. I have the same issue in all my tests using $httpBackend.



Is there any solution to this?


More From » angularjs

 Answers
23

Take this gist
https://gist.github.com/wilsonwc/8358542



angular.module('stateMock',[]);
angular.module('stateMock').service($state, function($q){
this.expectedTransitions = [];
this.transitionTo = function(stateName){
if(this.expectedTransitions.length > 0){
var expectedState = this.expectedTransitions.shift();
if(expectedState !== stateName){
throw Error(Expected transition to state: + expectedState + but transitioned to + stateName );
}
}else{
throw Error(No more transitions were expected! Tried to transition to + stateName );
}
console.log(Mock transition to: + stateName);
var deferred = $q.defer();
var promise = deferred.promise;
deferred.resolve();
return promise;
}
this.go = this.transitionTo;
this.expectTransitionTo = function(stateName){
this.expectedTransitions.push(stateName);
}

this.ensureAllTransitionsHappened = function(){
if(this.expectedTransitions.length > 0){
throw Error(Not all transitions happened!);
}
}
});


Add it to a file called stateMock in your test/mock folder, include that file in your karma config if it isn't already picked up.



The setup before your test should then look something like this:



beforeEach(module('stateMock'));

// Initialize the controller and a mock scope
beforeEach(inject(function ($state //other vars as needed) {
state = $state;
//initialize other stuff
}


Then in your test you should add



state.expectTransitionTo('project');

[#71018] Tuesday, May 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;