UI-router interfers with $httpbackend unit test, angular js

后端 未结 5 635
悲&欢浪女
悲&欢浪女 2020-11-29 01:59

This is a controller with a submit function:

$scope.submit = function(){   

 $http.post(\'/api/project\', $scope.project)
      .success(function(data, stat         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 02:28

    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');
    

提交回复
热议问题