这是一个带有提交功能的 Controller :
$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!");
}
}
});
将它添加到您的测试/模拟文件夹中名为 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
}
然后在你的测试中你应该添加
state.expectTransitionTo('project');
关于javascript - UI-router 干扰 $http 后端单元测试,angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23655307/