Angular injecting $service results in Unknown provider: $serviceProvider - angularjs

Why when I run this in the karma runner:
describe('Service tests', function () {
var DataServiceMock
var httpBackend;
beforeEach(angular.mock.module('app'));
beforeEach(angular.mock.inject(function( $httpBackend, $service, DataService, $injector){
results in this error
Error: [$injector:unpr] Unknown provider: $serviceProvider <- $service
http://errors.angularjs.org/1.2.1/$injector/unpr?p0=%24serviceProvider%20%3C-%20%24service
at /home/site/angular/angular.js:78:12
Edit 2____________________
I'm trying to mock the DataService for the dataHandlerService
describe('Service', function () {
var DataServiceMock
var httpBackend;
var testUrl = "test/";
beforeEach(angular.mock.module('app'));
beforeEach(angular.mock.inject(function(){
module(function ($provide) {
$provide.value('DataService', DataServiceMock)
})
}));
it('should have', inject(function(DataService) {
expect('DataService').not.toBe(null);
}));
and this error:
Error: Injector already created, can not register a module!
at workFn (/home/me/root/angular/angular-mocks.js:1985:15)

There is no $service. If you want to mock your service then you should do it by using $provide:
beforeEach(function () {
DataServiceMock= {}
DataServiceMock.doSomething = function() {}
module(function ($provide) {
$provide.value('DataService', DataServiceMock)
})
})

Related

"before each" hook: workFn error

I am running my tests with karma and phantom, Also I'm using mocha and sinon and tests are getting failed with below error:
EditResourceCategoryDialogTest EditResourceCategoryDialogController "before each" hook: workFn
Error: [$injector:modulerr] http://errors.angularjs.org/1.4.9/$injector/modulerr?p0=resourceofferingsApp&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20
Sample code:
define(function (require) {
"use strict";
var assert = require('chai').assert;
var sinon = require('sinon');
var angular = require('angular');
var angularMocks = require('angular.mocks');
require('resourceofferings/app');
require('dialog path');
describe('EditResourceCategoryDialogTest', function () {
beforeEach(module('resourceofferingsApp'));
describe('EditResourceCategoryDialogController', function () {
var $scope, ctrl;
//you need to inject dependencies first
beforeEach(inject(function ($rootScope, $injector) {
$scope = $rootScope.$new();
}));
it('initialization test (create mode)', inject(function ($controller) {
ctrl = $controller("EditResourceCategoryDialogController", {
$scope: $scope,
$uibModalInstance: null,
options: {
isEditMode: false
}
});
assert.equal($scope.isEditMode, false);
}));
});
});
});
Its exactly getting failed here:
beforeEach(inject(function ($rootScope, $injector) {
$scope = $rootScope.$new();
}));
Please help me to fix this issue..
Thanks in advance.
Try this ...
describe('controllers', function(){
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new(); // this is what you missed out
controller = $controller('EditResourceCategoryDialogController', {
$scope: scope,
$uibModalInstance: null,
options: {
isEditMode: false
}
});
}));
});
Update: According to Angular ...
A common reason why the module fails to load is that you've forgotten
to include the file with the defined module or that the file couldn't
be loaded.
Are you sure all needed files are loaded?

how to test constants in module?

I have the following module:
angular.module('config', []).constant('myconstant', somevalue);
I would like to unit test this so I created:
describe('Constants', function () {
var config;
beforeEach( inject(function (_config_) {
module('config');
config =_config_;
}));
it('should return settings',function(){
expect(config.constant('myConstant')).toEqual('somevalue');
});
});
Getting an error now:
Error: [$injector:unpr] Unknown provider: configProvider <- config
How can I fix this?
You should be injecting your constant like any other service and not your module. This works for me:
angular.module('config', []).constant('myconstant', 'somevalue');
describe('Constants', function () {
var myconstant;
beforeEach(module('config'));
beforeEach( inject(function (_myconstant_) {
myconstant =_myconstant_;
}));
it('should return settings',function(){
expect(myconstant).toEqual('somevalue');
});
});

$httpBackend is undefined although angular-mock is included

This is my test. I get error that $httpBackend is undefined.
describe("Objects Service", function () {
var $httpBackend, $rootScope, scope, datacontext, config;
beforeEach(function () {
module('agApp');
});
beforeEach(inject(function ($rootScope, _$httpBackend_, _datacontext_, _config_) {
scope = $rootScope.$new();
datacontext = _datacontext_;
$httpBackend = _$httpBackend_;
config = _config_;
}));
it("should call right API adress to get all objects", function () {
$httpBackend.whenGET('/api/objects').respond(200);
datacontext.objects.getObjects(function (data) {
$httpBackend.flush();
});
});
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectations();
$httpBackend.verifyNoOutstandingRequest();
});
});
3 specs, 1 failure
Spec List | Failures
Objects Service should call right API adress to get all objects
Error: [$injector:unpr] Unknown provider: configProvider <- config
http://errors.angularjs.org/1.3.9/$injector/unpr?p0=configProvider%20%3C-%20config
Error: [$injector:unpr] Unknown provider: configProvider <- config
http://errors.angularjs.org/1.3.9/$injector/unpr?p0=configProvider%20%3C-%20config
at http://localhost/WebRenter/Scripts/vendor/angular.js:64:20
at http://localhost/WebRenter/Scripts/vendor/angular.js:3995:21
at Object.getService [as get] (http://localhost/WebRenter/Scripts/vendor/angular.js:4142:53)
at http://localhost/WebRenter/Scripts/vendor/angular.js:4000:47
at getService (http://localhost/WebRenter/Scripts/vendor/angular.js:4142:53)
at Object.invoke (http://localhost/WebRenter/Scripts/vendor/angular.js:4174:13)
at Object.workFn (http://localhost/WebRenter/bower_components/angular-mocks/angular-mocks.js:2436:20)
at attemptSync (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:1741:24)
at QueueRunner.run (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:1729:9)
at QueueRunner.execute (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:1714:10)
Error: Declaration Location
at window.inject.angular.mock.inject (http://localhost/WebRenter/bower_components/angular-mocks/angular-mocks.js:2407:25)
at Suite. (http://localhost/WebRenter/Test/objects/repository.objects.Spec.js:9:16)
at addSpecsToSuite (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:725:25)
at Env.describe (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:695:7)
at jasmineInterface.describe (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:2969:18)
at http://localhost/WebRenter/Test/objects/repository.objects.Spec.js:4:1
TypeError: Cannot read property 'whenGET' of undefined
TypeError: Cannot read property 'whenGET' of undefined
at Object. (http://localhost/WebRenter/Test/objects/repository.objects.Spec.js:20:20)
at attemptSync (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:1741:24)
at QueueRunner.run (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:1729:9)
at QueueRunner.execute (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:1714:10)
at Spec.Env.queueRunnerFactory (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:608:35)
at Spec.execute (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:346:10)
at Object.fn (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:2059:43)
at attemptAsync (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:1771:24)
at QueueRunner.run (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:1726:9)
at QueueRunner.execute (http://localhost/WebRenter/Scripts/jasmine/jasmine.js:1714:10)
This is datacontext:
angular.module("agApp").factory("datacontext", ['$http', '$q', 'repositories', function ($http, $q, repositories) {
var RepoNames = ['objects', 'images', 'objectattributes', 'info', 'units', 'unitattributes']
var service = {
}
init();
return service;
function init() {
defineLazyLoadedRepos();
}
function defineLazyLoadedRepos() {
RepoNames.forEach(function (name) {/**/
Object.defineProperty(service, name, { //
configurable: true,
get: function () {///
var repo = repositories.getRepo(name); //samo prvi put a poslije može confugurable false
Object.defineProperty(service, name, {
value: repo,
configurable: false,
enumerable: true
});
return repo;
}///
});
//
}); /**/
}
} ]);
This is start of objects.repository file:
(function () {
var serviceId = 'repository.objects';
angular.module("agApp").factory(serviceId, ['$http', '$q', '$cacheFactory', 'repository.abstract', 'config', function ($http, $q, $cacheFactory, AbstractRepository, config) {
var entityName = 'objects';
var apiRootUrl = ROOT + "api/";
var cache = $cacheFactory("objectCache");
var cacheOn = config.cache.globalCache && config.cache.objectCache;
var _getObjects = function (object) {
var deferred = $q.defer();
$http.get(apiRootUrl + "objects").then(function (data, status, headers, config) {
deferred.resolve(data.data);
}, function (response) {
self._queryFailed(response);
deferred.reject();
});
return deferred.promise;
}
This is config:
(function () {
'use strict'
var agApp = angular.module('agApp');
var apiUrl = "api/";
//ROOT je definiran na layoutu
var viewsUrl = ROOT + 'App/Scripts/views';
var config = {
version: '0.0.1',
apiUrl: apiUrl,
viewsUrl: viewsUrl,
root:ROOT,
cache:{
globalCache:true,
objectCache:true,
objectAttrCache:true,
unitCache:true
}
};
agApp.value('config', config);
agApp.config(['$logProvider','$locationProvider', function ($logProvider,$locationProvider) {
$locationProvider.html5Mode({
enabled: true,
});
if ($logProvider.debugEnabled) {
$logProvider.debugEnabled(true);
}
} ]);
})();
Based on the information you've provided, first, look at the page that your first error message links to:
https://docs.angularjs.org/error/$injector/unpr?p0=configProvider%20%3C-%20config
It doesn't look like you're redefining your module or injecting a controller into a controller.
I think the most likely reason you're having this error (based on assuming there aren't other problems, and the fact that I had a similar problem) is that you either didn't include config in your karma.conf.js file, or if you did, you included it after your test. The order of files matters in Karma:
http://karma-runner.github.io/0.8/config/files.html
You've probably figured out your problem by now, but I had a similar one and would've appreciated an answer when looking for it.

Getting error in controller while unit testing using karma jasmine

I'm getting this error while I'm running unit test using Karma-Jasmine
ReferenceError: myModule is not defined
My sample test case is as follows..
describe("Unit Testing", function() {
beforeEach(angular.mock.module('myModule.common'));
var scope, ngTableParams, filter ,testTableParam;
it('should have a commonController controller', function () {
expect(myModule .common.controller('commonController ', function (commonController ) {
$scope:scope;
ngTableParams:ngTableParams;
$filter: filter;
tableParams: testTableParam
}
)).toBeDefined();
});});
I have injected the module name as myModule.common.
Can you please suggest a solution?
Try following code snippet it might help
describe('testing myModule.common', function() {
var $rootScope, $scope, $filter, $controller, ngTableParams, testTableParam;
beforeEach(module('myModule.common'));
beforeEach(function() {
inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
$filter = $injector.get('$filter');
testTableParam = $injector.get('testTableParam');
ngTableParams = $injector.get('ngTableParams');
$controller = $injector.get('$controller')('commonController ', {
$scope: $scope
});
});
});
it('testing commonController ', function() {
expect('commonController ').toBeDefined();
});
});
It will solve your problem

Mocking $resourceProvider in AngularJs & Jasmine

In my controller I am using $resource: ng.resource.IResourceService the could help me to fetch data from the server.
controllers.controller("testController", [
"$scope", "$resource", "$rootScope", "$http",
"$window", "$location", "resourceService",
function ($scope, $resource: ng.resource.IResourceService, $rootScope: IRootScope,
$http, $window, $location, resourceService: services.IResourceService) { ...//implementation
}]);
And here is my attempt of Jasmine unit test. However, I am getting
Error: [$injector:unpr] Unknown provider: $resourceProvider <- $resource
How would you mock $resourceProvider?
describe("testController Tests", function (): void {
var vm: createDailylog.IViewModel;
var $scope: ng.IScope;
var $rootScope;
var $httpBackend: ng.IHttpBackendService;
//var $injector = angular.injector(['ng', 'ngResource']);
var $resource = $injector.get('$resource');
beforeEach(function (): void {
module("controllers");
});
beforeEach(inject(function (_$controller_: ng.IControllerService,
_$httpBackend_, _$resource_, _$rootScope_: IRootScope, $injector) {
$httpBackend = _$httpBackend_;
//$resource = _$resource_;
this.$httpBackend = $httpBackend;
$rootScope = _$rootScope_.$new();
$rootScope.config = {
serverUrl: "https://test.domainName.net/",
serverVersion: "test",
title: "Test Server Reference"
};
//instantiating controller
vm = _$controller_('testController', {
$scope: $scope,
$resource: $injector.get("$resource"),
$rootScope: _$rootScope_,
$window: {},
$location: {}
});
}));
//afterEach(function () {
// $httpBackend.verifyNoOutstandingExpectation();
// $httpBackend.verifyNoOutstandingRequest();
//});
describe('when populate method is called', function () {
it("should create controller!", function () {
$httpBackend.flush();
expect(true).toBe(true);
});
});
);
});
});
Why do you need to mock $resource? You should only be mocking data, which is coming from $http; you seem to be doing that already.

Resources