【发布时间】:2017-01-04 07:51:43
【问题描述】:
在这个 Angular/Jasmine 测试中,我有一个控制器,它使用名为 http 的服务。该服务位于services 文件夹中名为http.js 的文件中。
问题(见下面的错误)是 Karma/Jasmine 没有找到 http 服务,即使我在 karma.conf.js 中明确声明了它。可能是什么问题?
PhantomJS 2.1.1 (Windows 8 0.0.0) Testing Bank management should retrieve bank list FAILED
Error: [$injector:unpr] http://errors.angularjs.org/1.4.8/$injector/unpr?p0=httpProvider%20%3C-%20http (line 41)
libs/angular/angular.min.js:41:146
d@libs/angular/angular.min.js:39:93
libs/angular/angular.min.js:41:198
d@libs/angular/angular.min.js:39:93
e@libs/angular/angular.min.js:39:363
workFn@libs/angular/angular-mocks.js:2439:26
inject@libs/angular/angular-mocks.js:2411:41
test/web/admin/banks/mngbanks.test.js:44:10
loaded@http://localhost:9876/context.js:151:17
undefined
TypeError: undefined is not an object (evaluating 'deferred.resolve') in test/web/admin/banks/mngbanks.test.js (line 70)
test/web/admin/banks/mngbanks.test.js:70:12
loaded@http://localhost:9876/context.js:151:17
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 3 of 3 (1 FAILED) (0.016 secs / 0.021 secs)
Warning: Task "karma:unit" failed. Use --force to continue.
karma.conf.js:
module.exports = function(config) {
config.set({
basePath: 'c:/apps/public/',
frameworks: ['jasmine'],
files: [
'libs/angular/angular.min.js',
'libs/angular/angular-mocks.js',
'app/web/app.js',
'app/services/http.js', // <-- service is in this file
'app/**/*.js',
'test/**/*.js'
],
exclude: [
],
preprocessors: {},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: true,
concurrency: Infinity
})
}
茉莉花测试:
describe('Testing management', function () {
var $scope;
var deferred;
var list = {
data: {
acc: 2,
bnks: [
{sk:1, nm:"Bank 1", dsc:"Bank 1 description",als:"BK1"},
{sk:2, nm:"Bank 2", dsc:"Bank 2 description",als:"BK2"},
{sk:3, nm:"Bank 3", dsc:"Bank 3 description",als:"BK3"}
]
}
};
var ConstantsMock = {
ReadMany: 'M'
};
function NgTableParamsMock() {
}
beforeEach(function () {
module(moduleName);
module(function ($provide) {
$provide.value('NgTableParams', NgTableParamsMock);
$provide.value('Constants', ConstantsMock);
});
inject(function($controller, _$rootScope_, $q, http, $timeout) {
$scope = _$rootScope_.$new();
console.log("scope:"+$scope)
deferred = $q.defer();
spyOn(http, 'call').and.returnValue(deferred.promise);
$controller('mngBanksCtl', {
$rootScope: _$rootScope_,
$scope: $scope,
$timeout: $timeout,
http: http,
NgTableParams: NgTableParamsMock,
Constants: ConstantsMock
});
});
});
it('should retrieve list', function () {
deferred.resolve(list);
$scope.$apply();
expect($scope.data).toBe(list);
});
});
【问题讨论】:
-
请添加你的茉莉花测试代码
-
添加了测试。
-
http服务在哪个模块下?
-
http服务在同一个模块,我整个应用只有一个模块
-
http 是您的服务/工厂的名称,对吗?您是否尝试使用 $injector 服务加载?
标签: angularjs jasmine karma-runner karma-jasmine