这是一个具有提交功能的控制器:
$scope.submit = function(){ $http.post('/api/project', $scope.project) .success(function(data, status){ $modalInstance.dismiss(true); }) .error(function(data){ console.log(data); }) } }
这是我的考验
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); });
我得到的错误是:
Error: Unexpected request: GET views/appBar.html
views / appBar.html是我的templateUrl:
.state('project', { url: '/', templateUrl:'views/appBar.html', controller: 'ProjectsCtrl' })
因此,以某种方式ui-router使我的$ httpBackend指向此位置而不是我的提交功能。使用$ httpBackend进行的所有测试都存在相同的问题。
有什么解决办法吗?
采取这个要点 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!"); } } });
将其添加到test / mock文件夹中的名为stateMock的文件中,如果尚未将其包含在您的业力配置中。
测试之前的设置应如下所示:
beforeEach(module('stateMock')); // Initialize the controller and a mock scope beforeEach(inject(function ($state //other vars as needed) { state = $state; //initialize other stuff }
然后在测试中,您应该添加
state.expectTransitionTo('project');