UI路由器干扰$ httpbackend单元测试,角度js

Joe*_*Joe 44 javascript angularjs angular-ui karma-runner angular-ui-router

这是一个具有提交功能的控制器:

$scope.submit = function(){   

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

这是我的考验

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);
  });
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

Error: Unexpected request: GET views/appBar.html
Run Code Online (Sandbox Code Playgroud)

views/appBar.html是我的templateUrl:

 .state('project', {
    url: '/',
    templateUrl:'views/appBar.html',
    controller: 'ProjectsCtrl'
  })
Run Code Online (Sandbox Code Playgroud)

所以不知何故,ui-router正在使我的$ httpBackend指向此而不是我的提交功能.在使用$ httpBackend的所有测试中,我遇到了同样的问题.

这有什么解决方案吗?

ros*_*wil 48

拿这个要点 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!");
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

将它添加到test/mock文件夹中名为stateMock的文件中,如果尚未获取,则将该文件包含在您的karma配置中.

测试前的设置应如下所示:

beforeEach(module('stateMock'));

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

然后在你的测试中你应该添加

state.expectTransitionTo('project');
Run Code Online (Sandbox Code Playgroud)

  • 真棒!我几乎一起跳过ui-router.做得好!您应该与ui-router伙伴分享这项工作,以便人们可以更好地找到它. (2认同)

Ron*_*ere 39

关于单元测试UI路由器的这个Github问题更全面地解释了正在发生的事情.

问题是$httpBackend.flush()触发广播然后触发其他情况stateProvider.

一个简单的解决方案可以是进行以下设置,如上面提到的Github线程中的@darinclark所提到的那样.如果您不需要测试状态转换,则此选项有效.否则请看看@ rosswil的答案,这个答案受到@Vratislav在Github上的回答的启发.

beforeEach(module(function ($urlRouterProvider) {
    $urlRouterProvider.otherwise(function(){return false;});
}));
Run Code Online (Sandbox Code Playgroud)

EDITED

感谢Chris T在评论中报告这一点,似乎是在v0.2.14之后?最好的方法是使用

beforeEach(module(function($urlRouterProvider) {
  $urlRouterProvider.deferIntercept();
}));
Run Code Online (Sandbox Code Playgroud)

  • UI-Router现在有一个`$ urlRouterProvider.deferIntercept()`函数.请参阅https://github.com/angular-ui/ui-router/issues/212#issuecomment-69974072 (12认同)
  • 这是最快的解决方案 (2认同)