Unit Testing in Jasmine - angularjs

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?

Related

How to unit test the angularjs injector, outside of a controller?

As part of an AngualrJS app, I have to retrieve user details from a REST api before bootstrapping the application.
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('../api/user').then(
function (response) {
if (response.user.valid) {
angular.bootstrap(document, ['app']);
}
},
function () {
window.location.href = '../userError.html';
}
});
I'm building the application using gulp, and have been trying to unit test this as follows
describe('unit test app config', function () {
beforeEach(function () {
module('app');
inject();
});
it('should log a message on calling the injector', function () {
spyOn(angular, 'injector').and.callThrough();
expect(angular.injector).toHaveBeenCalled();
});
});
but this is giving the following error: Expected spy injector to have been called.
How can I unit test this code? I just need to mock the $http service and test the success and failure functions

unable to inject module/service for unit test

I am new to TDD and am trying to wire up a test, and have been stuck on it for hours. I keep getting the following error:
[$injector:modulerr] Failed to instantiate module AuthInterceptor due to:
Error: [$injector:nomod] Module 'AuthInterceptor' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.5.8/$injector/nomod?p0=AuthInterceptor
at client/test/index.js:8237:13
at client/test/index.js:10251:18
at ensure (client/test/index.js:10175:39)
at module (client/test/index.js:10249:15)
at client/test/index.js:12786:23
at forEach (client/test/index.js:8490:21)
at loadModules (client/test/index.js:12770:6)
Here is my test:
import angular from 'angular';
import serviceModule from './auth.interceptor'
describe('wire.common.services', () => {
describe('AuthService', () => {
let AuthService;
beforeEach(angular.mock.module(serviceModule.name));
beforeEach(angular.mock.module(($provide) => {
$provide.factory('$q', () => ({}));
$provide.factory('$log', () => ({}));
}));
beforeEach(angular.mock.inject((_AuthService_) => {
AuthService = _AuthService_;
}));
it('should be a dummy test', () => {
expect(2).toEqual(2);
});
});
});
The actual code I'm testing:
export default function AuthInterceptor($q, $injector, $log) {
'ngInject';
return {
request(config) {
let AuthService = $injector.get('AuthService');
if (!config.bypassAuthorizationHeader) {
if (AuthService.jwtToken) {
config.headers.Authorization = `Bearer ${AuthService.jwtToken}`;
} else {
$log.warn('Missing JWT', config);
}
}
return config || $q.when(config);
},
responseError(rejection) {
let AuthService = $injector.get('AuthService');
if (rejection.status === 401) {
AuthService.backToDAS();
}
return $q.reject(rejection);
}
};
}
I don't understand why I'm getting this error - I provided all the dependencies for the service and am following what is outlined in the angular documentation. any help is appreciated!
Update, this is the code that I went with:
import angular from 'angular';
import AuthInterceptor from './auth.interceptor'
describe('Auth interceptor test', () => {
describe('AuthInterceptor test', () => {
let $httpBackend, $http, authInterceptor = AuthInterceptor();
beforeEach(angular.mock.module(($httpProvider, $provide) => {
$httpProvider.interceptors.push(AuthInterceptor);
$provide.factory('AuthService', () => ({
jwtToken: "hello",
backtoDAS: angular.noop
}));
}));
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
$http = $injector.get('$http');
}))
it('should have a request function', () => {
let config = {};
expect(authInterceptor.request).to.be.defined;
expect(authInterceptor.request).to.be.a('function');
})
it('the request function should set authorization headers', (done) => {
$httpBackend.when('GET', 'http://jsonplaceholder.typicode.com/todos')
.respond([{
id: 1,
title: 'Fake title',
userId: 1
}]);
$http.get('http://jsonplaceholder.typicode.com/todos').then(function(transformedResult) {
expect(transformedResult.config.headers.Authorization).to.be.defined;
expect(transformedResult.config.headers.Authorization).to.contain('Bearer')
done();
})
$httpBackend.flush();
});
it('should have a responseError function', () => {
expect(authInterceptor.responseError).to.be.defined;
expect(authInterceptor.responseError).to.be.a('function');
//TODO: test return value
// see that AuthService.backToDAS()
})
it('the error function should call backtoDAS', (done) => {
//the URL should be one that gives me a 401
$httpBackend.when('GET', 'https://wwws.mint.com/overview.event')
.respond([{
id: 1,
title: 'Fake title',
userId: 1
}]);
$http.get('https://wwws.mint.com/overview.event').then(function(transformedResult) {
console.log(transformedResult);
done();
}, function(error){
console.log(error);
done();
})
});
})
});
This means that AuthInterceptor Angular module wasn't defined (and by the way, relying on name is unsafe).
AuthInterceptor isn't a module but an injectable function. It can be tested in functional fashion as $http interceptor:
beforeEach(angular.mock.module(($httpProvider) => {
$httpProvider.interceptors.push(AuthInterceptor);
});
...
it('...', () => {
$httpBackend.when(...).respond(...);
$http.get(...).then((interceptedResult) => {
expect(interceptedResult)...
});
$rootScope.$digest();
});
or directly:
it('...', () => {
let interceptor = $injector.invoke(AuthInterceptor);
expect(interceptor).toEqual({
request: jasmine.any(Function),
requestError: jasmine.any(Function)
});
var config = { headers: {} };
interceptor.request(config);
expect(config)...
});
Services that produce side effects (AuthService, $log) should be stubbed.
This means that ng module is failing to load. :) And this happens while bootstrapping the app and ng module is first in a three element array: ng, ['$provide', function($provide) { ... }] and my own application module. It fails when loading the first one.
I've looked at console and I've copied this error message from it. There's no other error. None.
I hope you clicked that specific link and see that it doesn't give you any specific ideas about it. Unfortunately I've added this GitHub issue after exhausting other resources. I'm currently debugging angular code to get any further.

Angular unit test for a service with constants using Jasmine

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

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');
});
});

expect(service).toBeDefined throws error in Angular JS - TypeError: 'undefined' is not a function

I am new to Angular JS and trying to write a unit test for my service in mocha, but getting below error everytime it is run. Please suggest.
TypeError: 'undefined' is not a function (evaluating 'expect(InfoService).toBeDefined()')
Unit test :
describe('Unit: InfoService', function () {
var InfoService;
var httpMock;
beforeEach(angular.mock.module('app.Info'));
beforeEach(angular.mock.module(function ($provide) {
$provide.value('CONSTANT', {
DETAIL_URL:'/test/someurl/'
});
}));
beforeEach(inject(function($httpBackend,InfoService) {
InfoService = InfoService;
httpMock = $httpBackend;
}));
it('InfoService should exist', function(InfoService){
expect(InfoService).toBeDefined();
});
});

Resources