I have the following service with a constant:
angular.module('app',[]).constant('alertType',{
success:1,
error:0
})
.factory("dataService",dataService);
dataService.$inject = ['$timeout', 'alertType']
function dataService($timeout, alertType) {
return {
//some code related to the service
}
}
Here is the test case for the service to check if it is registered or not
describe('Testing "dataService" service', function() {
var _dataService;
beforeEach(function() {
module('app');
inject(function(dataService) {
_dataService = dataService;
});
});
it('Should be registered', function() {
expect(_dataService).toBeDefined();
});
});
For some reason it doesn't work. I get a very long error that looks something like this:
Error: [$injector:unpr] Unknown provider: dataServiceProvider <- dataService http://errors.angularjs.org/1.3.0/$injector/unpr?p0=dataServiceProvider%20%3C-%20dataService
Am I doing it right or is there anything wrong with this?
Try mocking your provider at the top of your describe block like so:
beforeEach(module($provide => {
$provide.constant('alertType',{
success: 1,
error: 0
});
}));
For more details please refer to this answer: Unknown Provider when unit testing filter
Related
I am testing a custom service made in angular JS where there is an error which is occurring. It is as follows:-
Error during loading: Uncaught ReferenceError: angular is not defined in http://localhost:63342/EmailTests/Unit%20Tests/jasmine-standalone-3.3.0/src/emailService.js line 3
Here is the code
describe('Email Service', function(){
var emailService;
beforeEach(function () {
module('bahmni.registration');
inject(function () {
emailService = $injector.get('emailService');
});
});
it('should have a valid Email ID',function () {
var parameters={
access_key : {parameter:'sdasdafassfa'},
smtp: {parameter:1}
};
var result=emailService.validateEmailService('https://apilayer.net/api/check',parameters,'someEmail');
expect(result.toEqual(true));
})
});
How can I solve this?
I have a module
export default angular.module('pfui.user', [])
.controller('ModifyUserController', ModifyUserController)
that has a controller
export default class ModifyUserController{
userid:string;
...
}
I'm trying to create a unit test that can test some methods in the controller that calls services to do some operation. This is my Karma script -
describe('ModifyUserControllerTester', function () {
var $controller;
beforeEach(angular.mock.module('ui.router'));
beforeEach(angular.mock.module('pfui.user'));
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
}));
describe('Test', function () {
it('test accessing controller', function () {
let $scope = {};
var controller = $controller('ModifyUserController', {
$scope: $scope
});
expect($scope['userid']).toBe(undefined);
});
});
});
When I run the test, I get an error
Error: [$injector:unpr] Unknown provider: UsersProvider <- Users <- ModifyUserController
Initially I was getting an error that $stateProvider was missing. So I added
beforeEach(angular.mock.module('ui.router'));
and that error went away.
This is my first attempt in writing a Karma test. I'm not sure what I am missing. Why is Karma looking for a Provider when I don't have one in the module? Any help is greatly appreciated.
Your question doesn't show any dependency injections to the ModifyUserController but going by the error you have posted it looks like you haven't provided the 'Users' Service to the controller.
describe('ModifyUserControllerTester', function () {
var $controller;
var mockUsers;
beforeEach(angular.mock.module('ui.router'));
beforeEach(angular.mock.module('pfui.user'));
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
}));
describe('Test', function () {
it('test accessing controller', function () {
//----define your mock dependency here---//
let mockUsers = jasmine.createSpyObj('mockUsers', ['user_method1',
'user_method2',...]);
let $scope = {};
var controller = $controller('ModifyUserController', {
$scope: $scope,
Users: mockUsers
});
expect($scope['userid']).toBe(undefined);
});
});
});
PS. Since its best practice for unit tests to be conducted in isolation, you should also consider providing a mock state provider vs importing the actual ui.router module
I have an AuthService that has a dependency on userService which comes from a different module
I'm trying to write a unit test that checks a property of the userService which I have mocked out and included using the $provide service in my test spec.
beforeEach(function() {
module('app.services');
//Need to provide userService since it lives in a different module
module(function ($provide) {
$provide.value('userService', function(){
return {
userLoggedIn: false
}
});
});
});
//Question - will injecting _userService_ pick up the mocked instance from above?
beforeEach(inject(function(_AuthService_, _userService_) {
authService = _AuthService_;
userService = _userService_;
}));
describe('some text', function() {
it('should make a get request to check the users token', function() {
$httpBackend.expectGET('/auth/checktoken').respond({});
authService.hasAccessToken();
$httpBackend.flush();
});
it('should set userService.userLoggedIn to be true', function() {
expect(userService.userLoggedIn).toBeTruthy();
});
});
My expectation on my userService fails since it comes back as undefined. What do I need to do in order to test my mocked out userService?
Thanks
UPDATE
Ok so based on the comments, I can get it to pass by organising my tests like so
describe('hasAccessToken', function() {
beforeEach(function(){
authService.hasAccessToken();
});
it('should make a get request to catalogues', function() {
$httpBackend.expectGET('/auth/checktoken').respond({});
$httpBackend.flush();
});
it('should set userService.userLoggedIn to be true', function() {
$httpBackend.expectGET('/auth/checktoken').respond({});
$httpBackend.flush();
expect(userService.userLoggedIn).toBeTruthy();
});
});
As you can see I'm trying to write a test for the expectGET and the userService separately, is this correct? Just seems quite verbose??
You are using the angular's value synthetic sugar for provider, but you supply a constructor, which should be used with the service syntax.
try to use the service constructor with the service syntax instaed:
beforeEach(module(function ($provide) {
$provide.service('userService', function(){
return {
userLoggedIn: false
}
});
});
or just use the service's instance with the value syntax:
beforeEach(module(function ($provide) {
$provide.value('userService', {
userLoggedIn: false
}
});
});
see angular docs: $provide
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');
});
});
I am having a lot of trouble getting dependencies provided properly for an AngularJS service.
I see a number of other posts with similar errors here on StackOverflow but none of them seem to resolve the issue.
Here is the app code:
cm.modules.app = angular.module('myApp', ['ngRoute', 'ngAnimate']);
myServiceName = function($http) {
// do stuff
};
myServiceName.prototype.value = 1;
cm.modules.app.service('defaultAlertFactoryA', myServiceName);
Here is the test code:
describe('test alertFactoryA', function() {
var $provide;
var mAlertFactoryA;
beforeEach(module(cm.modules.app));
beforeEach(angular.mock.module(function(_$provide_) {
$provide = _$provide_;
}));
beforeEach(function() {
inject(function($injector) {
mAlertFactoryA = $injector.get('defaultAlertFactoryA');
});
});
it('should work', function() {
expect(true).toBe(true);
});
});
Here is the error:
Error: [$injector:unpr] Unknown provider: defaultAlertFactoryAProvider
<- defaultAlertFactoryA
http://errors.angularjs.org/1.2.0-rc.2/$injector/unpr?p0=defaultAlertFactoryAProvider%20%3C-%20defaultAlertFactoryA
Question: How do I fix this so the test passes?
In order to bootstrap your module you need to provide its name
beforeEach(module('myApp'));
Demo
The following is what I used to get it working (finally)
beforeEach(function() {
module(cm.modules.app.name);
module(function($provide) {
$provide.service('defaultAlertFactoryA', myServiceName);
});
inject(function($injector) {
defaultAlertFactory = $injector.get('defaultAlertFactoryA');
});
});
Sounds like you need to include the service files in your karma.conf.js file
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-ui-router/release/angular-ui-router.js',
'app/app.js',
'app/controllers/*.js',
'app/services/*.js',
'tests/**/*.js'
],
If the are not included here they can't be accessed in the unit tests