我正在尝试为使用$ http和$ q的AngularJS服务编写单元测试。我过去没有遇到过这个问题,甚至还有单元测试。通过阅读SO中的所有帖子,它们似乎都没有解决我的具体情况,即我试图测试service
,而不是controller
。
经过多次尝试修复此问题后,我仍然遇到No pending request to flush
错误。我尽可能地证实,$ http正在被调用。
以下是现在的所有代码,在尝试了SO上的各种方法之后,以及AngularJS文档。
我想指出该服务是有效的,而不是在使用Karma和Jasmine时。
服务
(function(angular, undefined){
"use strict";
angular.module('module.http',[])
.service("noHTTP",['$q', '$http', function($q, $http){
this.configure = function(){
angular.noop();
}
this.createTransport = function(){
return new noREST();
}
function noREST(){
var SELF = this;
this.create = function(resourceURI, formdata){
var json = angular.toJson(formdata);
var deferred = $q.defer(),
req = {
method: "POST",
url: resourceURI,
data: json,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
withCredentials: true
};
$http(req)
.success(function(data){
console.log(angular.toJson(data) );
deferred.resolve(data.d);
})
.error(function(reason){
console.error(reason);
deferred.reject(reason);
});
return deferred.promise;
}
}
}])
;
})(angular)
测试数据
var CRUD = {
POST: {
request: {
url: "http://img.local/NoCacheManifest",
data: {
"TableName":"Addresses","EntityName":"Address","Count":60,"LastTransaction":"2015-03-23T13:50:52.16","Query":null,"StorageLocation":"indexedDB","IndexedDB":"{\"keys\": \"++\", \"pk\":\"AddressID\"}"
},
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
},
response: {
"odata.metadata": "http://img.local/odata/$metadata#NoCacheManifest/@Element",
"ID": 91,
"TableName": "Test",
"EntityName": "Test",
"Count": 60,
"LastTransaction": "2015-03-23T13:50:52.16",
"Query": null,
"StorageLocation": "indexedDB",
"IndexedDB": "{\"keys\": \"++\", \"pk\":\"AddressID\"}"
}
}
};
单元测试
describe("Testing service", function(){
var noHTTP, $httpBackend, $rootScope;
beforeEach(function(){
module("module.http");
inject(function($injector){
$httpBackend = $injector.get("$httpBackend");
noHTTP = $injector.get("noHTTP");
$rootScope = $injector.get("$rootScope");
})
});
describe("Testing INOCRUD transport inteface", function(){
it("should successfully post a new record to the create endpoint.", function(done){
var iNoCRUD = noHTTP.createTransport();
$httpBackend
.when("POST", CRUD.POST.request.url, angular.toJson(CRUD.POST.request.data))
.respond(201, CRUD.POST.response, CRUD.POST.request.headers );
$rootScope.$apply(function(){
iNoCRUD.create(CRUD.POST.request.url, CRUD.POST.request.data)
.then(function(data){
expect(data).toEqual(CRUD.POST.response);
done();
})
.catch(function(err){
console.log(err);
done();
});
});
$httpBackend.flush();
});
});
});
karma.config.js
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'bower_components/ng-lodash/build/ng-lodash.js',
'test/mock/*.*',
'test/http.spec.js',
'src/http.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['verbose'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};