这是一个带有提交功能的控制器:
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);
})
}
}
这是我的测试
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:
views/appBar.html is my templateUrl:
.state('project', {
url: '/',
templateUrl:'views/appBar.html',
controller: 'ProjectsCtrl'
})
所以不知何故 ui-router 让我的 $httpBackend 指向这个而不是我的提交函数.我在所有使用 $httpBackend 的测试中都遇到了同样的问题.
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.
有什么解决办法吗?
抓住这个要点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 的文件中,如果尚未选择该文件,请将该文件包含在您的 karma 配置中.
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');
这篇关于UI-router 干扰 $httpbackend 单元测试,角度 js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!