我是Karma的新手,所以这可能听起来微不足道。我有以下路线结构。
angular
.module('appRouter',['ui.router'])
.config(function($stateProvider,$urlRouterProvider){
$stateProvider
.state('settings.profile',{
url:'/profile',
templateUrl:'templates/profile.html'
})
.state('settings.account',{
url:'/account',
templateUrl:'templates/account.html',
controller:function(resolveData){
console.log(resolveData);
},
resolve:{
resolveData : function($http){
var root = 'https://jsonplaceholder.typicode.com';
return $http.get(root+'/posts/1').then(function(response){
return response.data;
});
}
}
});
$urlRouterProvider.otherwise('/settings/profile');
现在它的单元测试如下所示。请注意我也尝试测试解析功能
describe('UI Routerer Config For Account',function(){
var $state,$rootScope,$injector,$httpBackend,state = "settings.account";
beforeEach(function(){
module('appRouter');
});
beforeEach(inject(function(_$rootScope_,_$injector_,_$state_,_$httpBackend_,$templateCache){
$rootScope = _$rootScope_;
$state = _$state_;
$injector = _$injector_;
$httpBackend = _$httpBackend_;
$templateCache.put('templates/account.html','');
}));
it('should resolve "resolveData"',function(){
const state = $state.get('settings.account');
const resolveFn = state.resolve.resolveData;
$httpBackend.when('GET','https://jsonplaceholder.typicode.com/posts/1').respond(200,{
"userId": 1,
"id": 1,
"title": "...",
"body": "..."
});
$httpBackend.expectGET('https://jsonplaceholder.typicode.com/posts/1');
$httpBackend.flush();
const responseData = {
"userId": 1,
"id": 1,
"title": "...",
"body": "..."
};
expect(resolveData).toEqual(responseData);
});
});
但是这失败了:
should resolve "resolveData"
UI Routerer Config For Account
Error: No pending request to flush !
at Function.$httpBackend.flush (bower_components/angular-mocks/angular-mocks.js:1816:41)
at Object.<anonymous> (test/controllers/main-controller-spec.js:97:22)
我做错了什么?请解释一下。