Something strange is happening in jasmine. My code is working in Angular but when I execute $http.get in jasmin it is not working.
My factory is
app.factory('LocalizationHandler', ['$http', '$q', function ($http, $q) {
var self = this;
var res = {
SetNewCulture: function (culture)
{
console.log("Inside SetNewCulture");
self.culture = culture;
var res = "";
var defer = $q.defer();
$http.get("Scripts/Lib/Factories/Localization/CookinConcepts.json").success(function (response)
{
console.log("estoy dentro");
defer.resolve(response);
return defer.promise;
}).
error(function (e) {
console.log("ERROR");
}).
then(function (response)
{
console.log("OKEY");
self.LocalizationItems = response.data[self.culture];
});
return defer.promise;
}
}
self.LocalizationConstructor = function () {
res.SetNewCulture(res.GetCurrentCulture());
self.LocalizationItems = null;
self.culture = "ca-ES";
};
self.LocalizationConstructor();
return res;
}]);
My test is:
/// <reference path="../../../_references.js" />
describe("Factory - LocalizationHandler", function () {
var lh;
beforeEach(module('appCookIn'));
beforeEach(function () {
inject(function (LocalizationHandler) {
lh = LocalizationHandler;
});
});
it("LocalizationHandler - SetNewCulture", function () {
// Arrange
var expected = "es-ES";
// Act
var result = lh.SetNewCulture("es-ES");
// Assert
expect(result).not.toBe(expected);
});
});
with console.logI see only the next text in the OutPut window: Inside SetNewCulture.
SHOULD THE JSON FILE IN THE TEST PROJECT OR IN THE MAIN PROJECT?
Why in the test the function $http is not working? should geta json file with my culture?
Related
i want to call 2 api and want to store the response in the scope variable. but im not able to get the data in the scope variable. im using $q.all and service for calling the api
error
angular.js:88 Uncaught Error: [$injector:modulerr]
var app = angular.module('mymodule', []);
app.service('doorService', function ($http) {
this.get = function () {
var response = $http.get("url");
console.log(response);
alert("test");
return response;
};
});
app.service('waterService', function ($http) {
this.get = function () {
var response = $http.get("url");
return response;
};
});
app.controller('ctrl', function ($scope, $q, doorService, waterService) {
$scope.DoorData = [];
$scope.WatertankData = [];
loadData();
function loadData() {
var promiseDoor = doorService.get();
var promiseWater = waterService.get();
$scope.combineResult = $q.all([
promiseDoor,
promiseWater
]).then(function (resp) {
$scope.DoorData= resp[0].data;
$scope.WatertankData= resp[1].data;
});
}
});
function loadData() {
var promises = [
doorService.get(),
waterService.get()
];
$q.all(promises).then(function (resp) {
$scope.DoorData= resp[0].data;
$scope.WatertankData= resp[1].data;
$scope.combineResult = {
'DoorData': resp[0].data,
'WatertankData':resp[1].data
};
});
}
I want to mock my Angular JS method using Jamine. My code is:-
<script type="text/javascript">
var app = angular.module('mymodulee', []);
app.controller('mycontroller', function ($scope, $http, $log) {
$scope.ButtonClick = function (Id) {
var response = $http({
method: "get",
url: http://localhost:8080/Access/Tasks.DefectManagement/Services/Services.asmx/GetEligibilityDetails",
params: {
CovId: Id
}
});
return response;
}
});
And my Jasmine Test Case is:-
it('EligibilityDetails', function () {
var myserv, httpBackend;
inject(function ($httpBackend, _myserv_) {
myserv = _myserv_;
httpBackend = $httpBackend;
});
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
var $scope = {};
var controller = $controller('PatientDefectManagementCtrl', { $scope: $scope });
var returnData = {};
httpBackend.expectGET("http://localhost:8080/Access/Tasks.DefectManagement/Services/Services.asmx/GetEligibilityDetails").respond(returnData);
var returnedPromise = myserv.get(3904142);
var result;
returnedPromise.then(function (response) {
result = response.data;
});
httpBackend.flush();
expect(result).toEqual(returnData);
});
But its is giving an error. Can anyone please tell what changes I should make in my code so that i can run the test case using Jasmine Unit test.
Please help.
Thanks
describe('test',function(){
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();});
var myserv, httpBackend;
beforeEach(inject(function(_$httpBackend_,_myserv__){
myserv = _myserv_;
httpBackend = $httpBackend;});
it('EligibilityDetails', function () {
var $scope = {};
var controller = $controller('PatientDefectManagementCtrl', { $scope: $scope });
var returnData = {};
httpBackend.expectGET("http://localhost:8080/Access/Tasks.DefectManagement/Services/Services.asmx/GetEligibilityDetails").respond(returnData);
var returnedPromise = myserv.get(3904142);
var result;
returnedPromise.then(function (response) {
result = response.data;
});
httpBackend.flush();
expect(result).toEqual(returnData);});});
I am trying to create a service that passes data to controller.
I cannot see any errors in the console but yet the data won't show. What exactly am I doing wrong?
Service
app.service('UsersService', function($http, $q) {
var url = '/users';
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
parsePromise.resolve(data);
});
return parsePromise.promise;
});
Controller
app.controller('contactsCtrl',
function($scope, $routeParams, UsersService) {
// Get all contacts
UsersService.get().then(function(data) {
$scope.contacts = data;
});
});
success is now deprecated.
app.service('UsersService', function($http) {
var url = '/users';
this.get = function() {
return $http.get(url).then(function(response) {
return response.data;
});
}
});
you are referring to UsersService.get(), so you must define the .get() function to call:
app.service('UsersService', function($http, $q) {
var url = '/users';
this.get = function() {
var parsePromise = $q.defer();
$http.get(url).success(function(data) {
parsePromise.resolve(data);
});
return parsePromise.promise;
}
});
I am attempting to build a mock service so that my unit tests can verify certain functions are called and updated accordingly. Unfortunately I cannot get this to work.
Im currently getting an error undefined is not a function on this line:
spyOn(statusService, 'getModuleStatus').andCallThrough();
My actual service looks like this:
serviceStatusServices.factory('serviceStatusAppAPIservice', function ($http) {
var serviceStatusAppAPI = {};
serviceStatusAppAPI.getModuleStatus = function () {
return $http({
method: 'JSON',
url: '/settings/getservicestatusandconfiguration'
});
}
serviceStatusAppAPI.setModuleStatus = function (module) {
return $http({
method: 'POST',
url: '/settings/setservicestatusandconfiguration',
data: { moduleId: module.ModuleId, configData: module.ConfigValues }
});
}
return serviceStatusAppAPI;
});
My update function
serviceStatusControllers.controller('serviceStatusController', ['$scope', 'serviceStatusAppAPIservice', '$filter', '$timeout', function ($scope, serviceStatusAppAPIservice, $filter, $timeout) {
$scope.update = function () {
$scope.loading = true;
serviceStatusAppAPIservice.getModuleStatus().then(function (response) {
$scope.modules = $filter('orderBy')(response.data.moduleData, 'ModuleName')
...
My tests look like this
describe('ServiceStatusController', function () {
beforeEach(module("serviceStatusApp"));
var scope;
var statusService;
var controller;
var q;
var deferred;
// define the mock people service
beforeEach(function () {
statusService = {
getModuleStatus: function () {
deferred = q.defer();
return deferred.promise;
}
};
});
// inject the required services and instantiate the controller
beforeEach(inject(function ($rootScope, $controller, $q) {
scope = $rootScope.$new();
q = $q;
controller = $controller('serviceStatusController', {
$scope: scope, serviceStatusAppAPIservice: statusService });
}));
describe("$scope.update", function () {
it("Updates screen", function () {
spyOn(statusService, 'getModuleStatus').andCallThrough();
scope.update();
deferred.resolve();
expect(statusService.getModuleStatus).toHaveBeenCalled();
expect(scope.modules).not.toBe([]);
});
});
});
Also, how do I pass any mock data returned from the service to the caller. Currently in my model I do serviceStatusAppAPI.getModuleStatus(data) then use data.Data to get out the returned JSON.
I assume if you are doing something like this in your ctrl
scope.update = function() {
serviceStatusAppAPIservice.setModuleStatus(url).then(function (data) {
scope.modules = data;
})
};
Service which returns promise
.factory('serviceStatusAppAPI', function($http, $q) {
return {
getModuleStatus: function() {
var defer = $q.defer();
$http({method: 'GET', url: '/settings/getservicestatusandconfiguration'})
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
defer.resolve(data);
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
window.data = data;
});
return defer.promise;
}
};
});
So in you controller you will get data like this
serviceStatusAppAPI.getModuleStatus().then(function (data) {
$scope.modules = $filter('orderBy')(data.moduleData, 'ModuleName')
})
This is how you can run your unit test case
beforeEach(function() {
var statusService = {};
module('myApp', function($provide) {
$provide.value('serviceStatusAppAPIservice', statusService);
});
statusService.modalStatus = {
moduleData: [{ModuleName: 'abc'}, {ModuleName: 'def'}]
};
inject(function ($q) {
statusService.setModuleStatus = function () {
var defer = $q.defer();
defer.resolve(this.modalStatus);
return defer.promise;
};
statusService.getModuleStatus = function () {
var defer = $q.defer();
defer.resolve(this.modalStatus);
return defer.promise;
};
});
});
beforeEach(inject(function ($rootScope, $controller, _$stateParams_) {
scope = $rootScope.$new();
stateParams = _$stateParams_;
controller = $controller;
}));
var myCtrl = function() {
return controller('ServiceStatusController', {
$scope: scope,
});
};
it('should load status', function () {
myCtrl();
scope.update();
scope.$digest();
expect(scope.modules).toBe({
status: 'active'
});
});
The following is the code structure, iam using hot towel template for mvc project.
The script:
(function () {
'use strict';
var controllerId = 'EditEmployeeController';
angular.module('app').controller(controllerId, ['common', 'EmployeeService', EmployeeData]);
function EmployeeData(common, EmployeeService) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var $filter = common.$filter;
var logError = common.logger.getLogFn('app', 'error');
var vm = this;
vm.CountryCode;
vm.Country = [];
vm.State = [];
vm.employeeInfo = {};
//calling the method to get the Employee info
activate();
//calling the methods to get the States
GetStates();
function activate() {
var promises = [GetEmployeeInfo(),GetStates()];
common.activateController(promises, controllerId)
.then(function () { });
}
}
function GetEmployeeInfo() {
return EmployeeService.getEmpInfoForEdit(personId).then(function (data) {
vm.CountryCode = data.Country;
return vm.employeeInfo = data;
}
function GetStates() {
return EmployeeService.getStates(vm.CountryCode).then(function (data) {
return vm.State = data;
}
}
})();
EmployeeService.js
code snippet from EmployeeService.js
function getEmpInfoForEdit(personId) {
var EmpInfoForEdit = $resource('Employee/GetEmployeeDetailsForEdit', angular.fromJson(personId), { 'query': { method: 'POST', isArray: false } });
var deferred = $q.defer();
EmpInfoForEdit.query({}, function (response) {
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
})
return deferred.promise;
}
vm.CountryCode always shows null, though we are assigning a value to it in the GetEmployeeInfo method.Because unable to get the states.
please let me know can we get the data into vm.CountryCode ?
(function () {
'use strict';
var controllerId = 'EditEmployeeController';
angular.module('app').controller(controllerId, ['common', 'EmployeeService', EmployeeData]);
function EmployeeData(common, EmployeeService) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var $filter = common.$filter;
var logError = common.logger.getLogFn('app', 'error');
var vm = this;
vm.CountryCode=[];
vm.Country = [];
vm.State = [];
vm.employeeInfo = {};
//calling the method to get the Employee info
activate();
//calling the methods to get the States
GetStates();
function activate() {
var promises = [GetEmployeeInfo(),GetStates()];
common.activateController(promises, controllerId)
.then(function () { });
}
}
function GetEmployeeInfo() {
return EmployeeService.getEmpInfoForEdit(personId).then(function (data) {
vm.CountryCode = data.Country;
return vm.employeeInfo = data;
}
function GetStates() {
return EmployeeService.getStates(vm.CountryCode).then(function (data) {
return vm.State = data;
}
}
})();
If you want to work with the EmployeeService.getEmpInfoForEdit and EmployeeService.getStates returned data, you should inject $q in your controller and use the resolve data as the following example :
angular.module('app').controller(controllerId, ['$q', 'common', 'EmployeeService', EmployeeData]);
...
function GetEmployeeInfo() {
var deferred = $q.defer();
return EmployeeService.getEmpInfoForEdit(personId).then(function (data) {
deferred.resolve(data);
}
}
function GetStates() {
var deferred = $q.defer();
return EmployeeService.getStates(vm.CountryCode).then(function (data) {
deferred.resolve(data);
}
}
the issue is resolved by moving the GetStates method inside the then
var promises = [GetEmployeeInfo(),GetStates()];
common.activateController(promises, controllerId)
.then(function () { });
}
}
changed to
var promises = [GetEmployeeInfo()];
common.activateController(promises, controllerId)
.then(function () { GetStates() });
}
}