我正在开发一个有角度的 WebApp,由于后端还没有准备好,我正在使用一个假后端 ( $httpBackend
) 来测试我的 REST 请求。
它在 app.js 中是这样定义的:
// we want to use $httpBackend mock
app.config(function($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
});
// define our fake backend
app.run(function($http, $httpBackend, url) {
//Escape string to be able to use it in a regular expression
function regEsc(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
// Mocking the login request
//define the success var
var user = {username: "me@stuff.it", password: "pass"};
var userResponse = {
"succes": "true",
"user":{
"id":"8490394",
"username": "me",
"token": "asd8u09u900asduijjaijjHJ"
}
};
//success case
$httpBackend.whenPOST(url.login, user).respond(200,userResponse);
//other cases
$httpBackend.whenPOST(url.login).respond(403,{success: false, message: 'Wrong username or password'});
//let pass all views request
$httpBackend.whenGET(function(string){
console.log(string);
return true;
}).passThrough();
$httpBackend.whenGET( RegExp( regEsc( "views/" ) ) ).passThrough();
});
当我运行应用程序时它可以正常工作grunt serve
当我尝试运行我写的测试(在 Jasmine 中并通过 Karma 执行)时,问题就开始了,这里是一个示例测试:
'use strict';
describe('Service: Loginservice', function () {
// load the service's module
beforeEach(module('cmmApp'));
// instantiate service
var Loginservice, $rootScope, $httpBackend, url;
beforeEach(inject(function (_Loginservice_, _$rootScope_ , $injector, _url_) {
Loginservice = _Loginservice_;
$rootScope = _$rootScope_;
url = _url_;
//questo serve per iniettare httpBackend
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('POST', url.login, {username: "me@stuff.it",password:"pass"}).respond({success: true, user:{"id":"8490394","username": "me","token": "asd8u09u900asduijjaijjHJ"}});
$httpBackend.whenPOST(url.login).respond(403, {success: false, message: 'Wrong username or password'});
}));
it('should return user object', function () {
var f;
//se i valori sono corretti ritona un oggetto che contiene l'utente
inject(function(Loginservice, $rootScope){
Loginservice.login({username:"me@stuff.it",password:"pass"}).then(function(res){
f = res;
}); //end login
//this trigger the promise
$rootScope.$digest();
//this trigger the http request
$httpBackend.flush();
expect(f).toEqual({success: true, user:{"id":"8490394","username": "me","token": "asd8u09u900asduijjaijjHJ"}});
}); //end inject
});
如果我从 app.js 中删除虚假的后端配置,它们会完美运行,而不是将其留在那里 Karma 报告:Error: No pending request to flush !
我认为这是因为 app.js 中声明的拦截器被触发并阻止在请求中触发测试中定义的 $httpBackend。
关于如何解决这个问题的任何想法?
提前致谢