AngularJS: mocking the service in a controller using Jasmine - angularjs

Could you please help me to write down the Jasmine(2.0) test code for mock of the service in a Controller as below.
readJsonFactory.js
angular.module('myAssignmentTaskApp')
.factory('readJsonFactory', function ($http) {
var userExists = false;
var responseData = [];
return $http.get('../json/AutoTestDB1.json').then(function (response) {
for (var i=0; i<response.data.StatusTable.length; i++){
responseData.push(response.data.StatusTable[i].RunId);
}
return response;
}).catch(function (error) {
//
})
});
The Controller file readjson.js is as below.
angular.module('myAssignmentTaskApp')
.controller('ReadjsonctrlCtrl', function ($scope,readJsonFactory,$location) {
var testCaseNameFromReadJsonFactory = [];
readJsonFactory.then(function (response) {
for (`var i=0;i<response.data.StatusTable.length;i++`){
testCaseNameFromReadJsonFactory.push(response.data.StatusTable[i].TestScenario);
}
}
})
AutoTestDB1.json
{
"StatusTable": [
{
"RunId": "bah_regression_alternateFlights",
"TestScenario": "BAH - Change Default Search Options",
"Area": "Yes",
"TestCases": [
{
"TestID": "",
"TestName": "VerifyCarDepotPageIsDisplayed_Test",
"Status": [
{
"Release": " R301",
"Runner": "yes",
"Status": "Passed",
"details": [
{
"ResponseTime": "1m 26s 702ms",
"Status": "Passed",
"RecordData": 1511519114413
}
]
}
]
}
]
}
]
}
Please post an apporopriate spac.js file.
Thanks in advance.

You do use the following to mock your service
beforeEach(function() {
angular.mock.module('myAssignmentTaskApp', ($provide) => {
const mockReadJsonFactory = {
};
$provide.constant('readJsonFactory', mockReadJsonFactory);
});
});

Related

Push nested json values to array using node js

I need to show my json results into nested array format:
{
"state": [
{
"stateName": "tamilnadu"
}
],
"city": [
{
"cityName": "chennai"
}
]
}
This is my code. I'm new in node development
exports.stateId = function (req, res) {
state.find(req.body.countryId, function() {
var query = N1qlQuery.fromString('SELECT stateId,stateName FROM travel _type='state'');
myBucket.query(query, async function(err, result) {
var state=[];
await result.forEach(ele => {
var item= {
stateName:ele.stateName
}
if(ele.stateName != undefined)
state.push(item);
});
res.send({state});
});
});
};
exports.cityId = function (req, res) {
city.find(req.body.stateId, function() {
var query = N1qlQuery.fromString('SELECT cityId,cityName FROM travel where _type="city"');
myCluster.query(query, async function(err, result) {
var city=[];
await result.forEach(ele => {
var item= {
cityName:ele.cityName
}
if(ele.cityName != undefined)
city.push(item);
});
res.send({city});
});
});
};
Currently i will get results like two different array. i need to merge json results into single nested data
If you have the following data:
const data_1 =
{
"state": [
{ "stateName": "tamilnadu" }
]
};
const data_2 =
{
"city": [
{ "cityName": "chennai" } ]
};
and your desired object is:
{
"state": [
{
"stateName": "tamilnadu"
}
],
"city": [
{
"cityName": "chennai"
}
]
}
then you can use Object.assign method:
let desired = Object.assign({}, data_1, data_2);
console.log(`desired: `, desired)

How to update local json file in angularjs

How do I update local json file using angularjs. My file name is data.json which is location in project folder.
I tried this below way
var data = [{
"Numbers": {
"Number": {
"_Id": "1",
"__text": "201"
}
}
}];
var jsonFileName = "data.json"
factory.updateJsonDataByFileName = function (jsonFileName, data) {
$http.post(jsonFileName, data).then(function successCallback(response) {
var jsonResult = response.data;
deferred.resolve(jsonResult);
}, function errorCallback(error) {
deferred.reject(error);
});
return deferred.promise;
}
My JSON File looks like this below
{
"Numbers": {
"Number": {
"_Id": "1",
"__text": "200"
}
}
}

angular service test fails to return required response

I am trying to write tests for angular service using jasmine and karma. I have the following code for my service call:
angular.module('omdb', [])
.factory('myservice', MyService);
MyService.$inject = ['$http'];
function MyService($http) {
var vm = this;
var service = {};
service.getData = function() {
return $http.get('omdb/mydata.json').then(function(response) {
return response.data;
});
};
return service;
};
I am tesitng it using the following file for spec as:
describe('myservice', function() {
var mockservicedata = [{
"name": "value1",
"id": "1"
}, {
"name": "value2",
"id": "2"
}, {
"name": "value3",
"id": "3"
}];
var myservice = {};
beforeEach(module('omdb'));
beforeEach(inject(function(_myservice_) {
myservice = _myservice_;
}));
it('should return search myservice data', function() {
expect(myservice.getData()).toEqual(mockservicedata);
});
});
which basically throws an error as:
Expected d({ $$state: Object({ status: 0 }) }) to equal [ Object({ name: 'value1', id: '1' }), Object({ name: 'value2', id: '2' }), Object({ name: 'value3', id: '3' }) ].
stack#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1482:17
buildExpectationResult#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1452:14
Env/expectationResultFactory#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:583:18
Spec.prototype.addExpectationResult#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:324:29 addExpectationResult#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:533:16
Expectation.prototype.wrapCompare/<#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1406:7
#http://localhost:59239/movie-app/spec/omdb/myservice.spec.js:14:9
attemptSync#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1789:9
QueueRunner.prototype.run#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1777:9 QueueRunner.prototype.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1762:5
Env/queueRunnerFactory#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:627:7
Spec.prototype.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:353:5 executeNode/<.fn#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:2360:32 attemptAsync#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1819:9
QueueRunner.prototype.run#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1774:9
QueueRunner.prototype.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1762:5
Env/queueRunnerFactory#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:627:7
executeNode/<.fn#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:2345:13 attemptAsync#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1819:9
QueueRunner.prototype.run#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1774:9
QueueRunner.prototype.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1762:5
Env/queueRunnerFactory#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:627:7
TreeProcessor/this.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:2209:7
Env/this.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:678:7
window.onload#http://localhost:59239/movie-app/lib/jasmine-2.3.4/boot.js:110:5
I don't understand why it does not return data to the test. please help
Calling myservice.getData() won't actually give you the data you're expecting.
Since your getData method from MyService relies on $http's get method, you should be mocking it and then expecting that data returned.
So your test case should be like:
describe('myservice', function() {
var mockservicedata = [{
"name": "value1",
"id": "1"
}, {
"name": "value2",
"id": "2"
}, {
"name": "value3",
"id": "3"
}];
var myservice = {};
beforeEach(module('omdb'));
beforeEach(inject(function(_myservice_, _$httpBackend_) {
myservice = _myservice_;
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', "omdb/mydata.json").respond({
status: 200,
data: mockservicedata
});
}));
it('should return search myservice data', function() {
var response = myservice.getData()
response.then(function(response) {
expect(response.data).toEqual(mockservicedata);
});
$httpBackend.flush();
});
});
Hope this helps.
getData() will never return data instead it will return promise object.
If you want to test it then firstly you would have to mock the data for service then you can call it and match the result in the success handler.
Code is attached below:
describe('myservice', function() {
var mockservicedata = [{
"name": "value1",
"id": "1"
}, {
"name": "value2",
"id": "2"
}, {
"name": "value3",
"id": "3"
}];
var myservice, httpBackend;
beforeEach(module('omdb'));
beforeEach(inject(function(_myservice_, $httpBackend) {
myservice = _myservice_;
httpBackend = $httpBackend;
}));
it('should return search myservice data', function() {
httpBackend.when("GET", "omdb/mydata.json").respond(mockservicedata);
var promise = myservice.getData();
promise.then(function(response) {
expect(response.data).toEqual(mockservicedata);
});
httpBackend.flush();
});
});

Stuck: AngularJs using factory with http call to json

I am struck and not able to understand the issue here.
I created a factory using http service call to my json file
Factory (accountInfo.json):
appRoot.factory('accountInfo', ['$http', function($http) {
return $http.get('../../accountInfo.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
controller(AccountsController.js)
appRoot.controller('AccountsController', ['$scope', 'accountInfo', function($scope, accountInfo){
accountInfo.success(function(data) {
$scope.rows = data;
});
$scope.totals = {
name: '',
marketValue: 0,
cash: 0,
legend: 'none'
};
for (var i = 0; i < $scope.rows.length; i++) {
$scope.totals.marketValue += $scope.rows[i].marketValue;
$scope.totals.cash += $scope.rows[i].cash;
}
$scope.addAccount = function() {
$scope.rows.push({
name: 'New Account',
marketValue: Math.random() * 100000,
cash: Math.random() * 400000,
legend: 'cyan'
});
}
}]);
My json (accountInfo.json)
[{
"name": "Brokerage Account 3",
"marketValue": 1999990,
"cash": 1995826,
"legend": "orange"
},
{
"name": "Account 3",
"marketValue": 1949990,
"cash": 1695856,
"legend": "darkorange"
},
{
"name": "Brokerage Account 1",
"marketValue": 1349990,
"cash": 1595866,
"legend": "red"
},
{
"name": "Brokerage Account 4",
"marketValue": 155990,
"cash": 160826,
"legend": "blue"
},
{
"name": "Brokerage Account 2",
"marketValue": 74560,
"cash": 19956,
"legend": "gray"
},
{
"name": "Account 4",
"marketValue": 55006,
"cash": 53006,
"legend": "salmon"
},
{
"name": "Account 13",
"marketValue": 37340,
"cash": 0,
"legend": "green"
},
{
"name": "Joint Account 1",
"marketValue": 28308,
"cash": 4167,
"legend": "darkblue"
},
{
"name": "Joint Account 2",
"marketValue": 10000,
"cash": 10000,
"legend": "teal"
}]
Error I am receiving is "$scope.rows is undefined"
Controller is not able to access $scope.rows outside success function.
Thanks :)
You need to resolve the promise in your controller, not in your factory, just return the promise:
appRoot.factory('account', ['$http', function($http) {
return {
info: function () {
return $http.get('../../accountInfo.json');
}
}
}]);
Then in your controller do:
appRoot.controller('AccountsController', ['$scope', 'account', function($scope, account){
account.info()
.success(function(data) {
$scope.rows = data;
})
.error(function(err) {
return err;
});
}]);
FYI, the success and error methods are deprecated:
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
See: https://docs.angularjs.org/api/ng/service/$http
Use the then method:
account.info().then(
function resolved (response) {
$scope.rows = response.data;
},
function rejected (response) {
alert(response.status + ': ' + response.statusText);
}
);
Here's a working example of the concept: http://plnkr.co/edit/UtJDpvBKKYl4rBzgXYo4?p=preview
You should return a function which fetches the data when you call it like so:
appRoot.factory('accountInfo', ['$http', function($http) {
return {
fetchData: fetchData
};
function fetchData() {
return $http.get('../../accountInfo.json');
}
}]);
then in your controller you can do:
accountInfo.fetchData()
.then(
function(data) {
console.log(data);
},
function(error) {
console.log(error);
}
);
Thank you all for the help.
I solved my issues by bootstraping the app. I was not able to access my data initially since the http call was not completed.
angular.element(document).ready(function() {
angular.bootstrap(angular.element(document), ['app']);
});

why httpbackend not working in angular?

I am trying to test $http webservice using $httpBackend ? I am getting a error in that . how to test service using $httpbackend ?
here is my code
http://plnkr.co/edit/S3LFymv8hrxtatWaCv1A?p=preview
it('call http service', function() {
authRequestHandler = httpBackend.when('GET', 'data.json')
.respond([{
"name": "hello"
}, {
"name": "hello12"
}, {
"name": "hello22"
}, {
"name": "hello45"
}]);
httpBackend.flush();
service.callData().then(function(response) {
console.log(response)
expect(response.data.length).toBe(4)
})
})
Try this
authRequestHandler = httpBackend.when('GET', 'data.json')
.respond([{
"name": "hello"
}, {
"name": "hello12"
}, {
"name": "hello22"
}, {
"name": "hello45"
}]);
service.callData().then(function(response) {
console.log(response)
expect(response.data.length).toBe(4)
})
httpBackend.flush();

Resources