Property '$' of object is not a function jasmine - javascript

So when I try and run my jasmine tests, i get this error on every test:
TypeError: Property '$' of object [object Object] is not a function
at jasmine.Fixtures.cleanUp (http://localhost:8234/src/target/test-classes/frontend/thirdParty/js/com/github/velesin/jasmine-jquery/0.0.0/jasmine-jquery-0.0.0.js:117:3)
at null.<anonymous> (http://localhost:8234/src/target/test-classes/frontend/thirdParty/js/com/github/velesin/jasmine-jquery/0.0.0/jasmine-jquery-0.0.0.js:548:25)
at jasmine.Block.execute (http://localhost:8234/?:1152:19)
at jasmine.Queue.next_ (http://localhost:8234/?:2184:33)
at jasmine.Queue.start (http://localhost:8234/?:2137:10)
at jasmine.Spec.execute (http://localhost:8234/?:2464:16)
at jasmine.Queue.next_ (http://localhost:8234/?:2184:33)
at onComplete (http://localhost:8234/?:2180:20)
at jasmine.Spec.finish (http://localhost:8234/?:2438:7)
at null.onComplete (http://localhost:8234/?:2465:12)
I've seen the various posts and SO's about jquery running in noConflict mode and that I need to use jQuery throughout my code, but the code I'm testing doesnt have any $'s in it.
code:
$provide.factory('corsHttpInterceptor', ['$q', '$window', '$exceptionHandler', '$rootScope', 'jq360', function($q, $window, $exceptionHandler, $rootScope, jq360){
var corsHttpInterceptor,
ieCorsTimeoutTime;
function fixConfigForXdr(config)
{
if (config.method.toUpperCase() === "PUT")
{
config.method = "POST";
if (angular.isDefined(config.params))
{
config.params._method = "put";
}
else
{
config.params = {_method: "put"};
}
}
else if (config.method.toUpperCase() === "DELETE")
{
config.method = "GET";
if (angular.isDefined(config.params))
{
config.params._method = "delete";
}
else
{
config.params = {_method: "delete"};
}
}
}
function getResponseDataForXdr(xdr)
{
var responseData = xdr.responseText;
if ("application/json" === xdr.contentType)
{
responseData = angular.fromJson(responseData);
}
return responseData;
}
function getIEUrl(config)
{
var url = config.url;
if (angular.isDefined(config.params) && !angular.equals(config.params, {}))
{
if (-1 === url.indexOf("?"))
{
url += "?";
}
else
{
url += "&";
}
url += jq360.param(config.params);
}
return url;
}
corsHttpInterceptor = {
request: function(config){
var deferred,
promise,
xdr;
if ('withCredentials' in new $window.XMLHttpRequest())
{
return config;
}
else if (angular.isDefined($window.XDomainRequest))
{
config.method = angular.uppercase(config.method);
deferred = $q.defer();
//this promise already has the then function so don't need to add it
promise = deferred.promise;
try
{
xdr = new $window.XDomainRequest();
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "new XDomainRequest()");
}
try
{
fixConfigForXdr(config);
xdr.open(config.method, getIEUrl(config));
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "xdr.open");
}
xdr.onprogress = function() {}; //http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/30ef3add-767c-4436-b8a9-f1ca19b4812e/
xdr.ontimeout = function() {};
xdr.onload = function() {
try
{
var responseData = getResponseDataForXdr(xdr);
deferred.resolve({data: responseData, status: 200});
$rootScope.$apply();
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "xdr.onload");
}
};
xdr.onerror = function() {
try
{
deferred.reject({data: "", status: 500});
$rootScope.$apply();
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "xdr.onerror");
}
};
xdr.timeout = 0;
$window.setTimeout(function() { //IE CORS requests are inconsistent without the setTimeout. Reference: http://stackoverflow.com/questions/5250256/inconsistent-ajax-xdr-response-from-ie
try
{
if ("GET" === config.method)
{
xdr.send();
}
else
{
xdr.send(angular.toJson(config.data));
}
}
catch(e)
{
$exceptionHandler(new Error("CRITICAL: " + e.message), "xdr.send");
}
}, ieCorsTimeoutTime);//TEMPORARY way to dynamically set the timeout time for IE CORS requests
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status);
});
return promise;
};
return promise;
}
else
{
throw new Error("Browser doesn't support needed functionality.");
}
},
response: function(response){
return response;
},
responseError: function(rejection){
return $q.reject(rejection);
},
ieCorsTimeoutTime: ieCorsTimeoutTime
};
return corsHttpInterceptor;
}]);
test:
'use strict';
var mockAppbaseModule;
describe('appbaseWithCors', function(){
mockAppbaseModule = angular.module("appbase", []);
beforeEach(module(function($provide, $exceptionHandlerProvider) {
$provide.provider('jq360', function() {
this.$get = function() {
return $;
};
});
$exceptionHandlerProvider.mode('log');
}));
beforeEach(module('appbaseWithCors'));
describe("corsHttpInterceptor", function () {
var successCallback = null;
var errorCallback = null;
var successResponse = {foo: 'blah'};
var errorResponse = {errorCode: 123, appServer: 1};
beforeEach(inject(function() {
successCallback = jasmine.createSpy("successCallback");
errorCallback = jasmine.createSpy("errorCallback");
}));
var appStatus;
describe("Standard CORS", function () {
beforeEach(inject(function($window){
appStatus = {
appBaseUrl : "",
appServer: 1,
token: "TEST_TOKEN"
};
spyOn($window, "XMLHttpRequest").andReturn({withCredentials: 'foo'});
}));
it ("should call the error function when there is an error code in the response data", inject(function($http, $httpBackend) {
$httpBackend.expectGET("TEST_URL").respond(403, errorResponse);
var config = {method: "get", url:"TEST_URL"};
$http(config).success(successCallback).error(errorCallback).then(successCallback, errorCallback);
$httpBackend.flush();
expect(successCallback).not.toHaveBeenCalled();
expect(errorCallback).toHaveBeenCalledWith({data: errorResponse, status: 403, headers: jasmine.any(Function), config: jasmine.any(Object)});
}));
}));
}));
}));

Related

Function is not recognized by another function in angularjs

During loading of the partial Html with controller, my function named $scope.actionViewVisitors() is recognized and runs without errors. But whenever I use it inside another function on the same controller, it gives me an error:
TypeError: $scope.actionViewVisitors is not a function. Please see my code below:
angular.module("Visitor.controller", [])
// ============== Controllers
.controller("viewVisitorController", function ($scope, $rootScope, $http, viewVisitorService, viewAccountService, DTOptionsBuilder) {
$scope.visitorList = null;
$scope.viewAccountDetail = null;
$scope.avatar = null;
$scope.visitorDetail = null;
$scope.visitorBtn = "Create";
$scope.actionViewAccount = function () {
$scope.actionViewAccount = viewAccountService.serviceViewAccount()
.then(function (response) {
$scope.viewAccountDetail = response.data.account;
$scope.avatar = "../../avatars/" + response.data.account.AccountId + ".jpg";
})
}
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withDisplayLength(10)
.withOption('bLengthChange', false);
// THIS ONE IS NOT RECOGNIZED
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}
// I DON'T GET ANY ERROR HERE
$scope.actionViewVisitors();
$scope.actionViewAccount();
$scope.createVisitor = function () {
$scope.statusMessage = null;
if ($scope.visitorBtn == "Create") {
$scope.createVisitor = viewVisitorService.serviceCreateVisitor($scope.visitorDetail)
.then(function (response) {
if (response.data.response == '1') {
bootbox.alert({
message: "Successfully created a new visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
} else if (response.data.response == '0') {
bootbox.alert({
message: "Failed in creting visitor.",
size: 'small',
classname: 'bb-alternate-modal'
});
}
});
debugger;
$scope.visitorDetail = undefined;
// I GET THE ERROR WHEN I CALL THIS METHOD
$scope.actionViewVisitors();
}
}
})
// ============== Factories
.factory("viewVisitorService", ["$http", function ($http) {
var fac = {};
fac.serviceViewVisitors = function () {
return $http({
url: '/Visitor/ViewVisitors',
method: 'get'
});
}
fac.serviceCreateVisitor = function(visitor) {
return $http({
url: '/Visitor/CreateVisitor',
data: { visitor: visitor },
method: 'post'
});
}
return fac;
}])
You are overwriting the function with Promise in the following line, thus the error is correct
$scope.actionViewVisitors = function () {
$scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
Remove $scope.actionViewVisitors =
$scope.actionViewVisitors = function () {
viewVisitorService.serviceViewVisitors()
.then(function (response) {
$scope.visitorList = response.data.visitorList;
});
}
On the first call to the function you are changing it from a function to a Promise. Maybe you want to be returning the result instead?
$scope.actionViewVisitors = function () {
return viewVisitorService.serviceViewVisitors()
.then(function (response) {
debugger;
$scope.visitorList = response.data.visitorList;
});
}

JSON.parse unexpected end of input error in NodeJS MailParser

I am executing a code in NodeJS child_process.
I used MailParser of Andris9.
I used console.log(JSON.stringify({obj:mail_object})); to get the data of mail_object to the parent.
In the parent, I have this code, JSON.parse(retVal);.
The error came up is "Unexpected end of Input".
This error only shows when the email I received is having an attachment.
If the email doesnt have attachment, there is no error.
Here is the parent method,
getEmails(){
let workerProcess = child_process.spawn('node', [basePath+'imports/workers/retrieveEmail.js']);
workerProcess.stdout.on('data', function (data) {
try{
let retVal = new Buffer(data).toString();
retVal = JSON.parse(retVal);
console.log(retVal);
if(typeof retVal.err == "undefined"){
console.log(retVal.obj.from[0].address);
Fiber(function () {
var objs = [];
if (typeof retVal.obj.attachments !== "undefined") {
console.log("Test passed");
retVal.obj.attachments.forEach(function (attachment) {
let future = new Future();
Fiber(function () {
Files.write(attachment.content, {
fileName: attachment.fileName,
type: attachment.contentType
}, function (error, fileRef) {
if (error) {
future.throw(new Meteor.Error(500, error.message));
} else {
...
}
});
}).run();
var bool = true;
if (bool = future.wait())
objs.push(bool);
});
}
...
}).run();
}else{
console.log(retVal.err);
}
}catch(e){
console.log(e);
}
});
workerProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
workerProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});
},
I removed some unnecessary codes.
Here is my retrieveEmail.js,
...
client.on("retr", function (status, msgnumber, data, rawdata) {
if (status === true) {
var mailparser = new MailParser({
streamAttachments: false
});
var timeStamp = Math.floor(Date.now());
mailparser.on("attachment", function (attachment, mail) {
console.log(JSON.stringify({err:"testpassed1"}));
});
mailparser.on("end", function (mail_object) {
console.log(JSON.stringify({err:"testpassed2"}));
console.log(JSON.stringify({obj:mail_object}));
});
mailparser.write(data);
mailparser.end();
client.dele(msgnumber);
} else {
console.log("RETR failed for msgnumber " + msgnumber);
client.quit();
}
});
...

angularjs rewrite controller without factory

i'm developing an app that received from a server a JSON array and divided data in a specific way, i've a portion of code that works if i use it alone but if i tried to insert it in an application it doesn't work.
This is my code:
ionicApp.controller('DefaultController', DefaultController)
.factory('dataService', dataService);
DefaultController.$inject = ['dataService', '$http'];
function DefaultController(dataService, $http) {
var vm = this;
console.log("Dentro ctrl");
getEvents();
function getEvents() {
console.log("Dentro getEvents");
return dataService.getEvents()
.then(function (data) {
console.log("data: " + data);
vm.data = data;
console.log("vm.data: " + vm.data);
return vm.data;
});
}
vm.submit = function (){
console.log("funzione");
console.log(vm.form);
var data = vm.form; // IMPORTANT
//console.clear();
var link = 'http://localhost/<path>/api/apiDoFix.php';
var mail = window.localStorage.getItem("mail");
var scelta = window.localStorage.getItem("scelta");
console.log(data);
console.log ("EMAIL" + mail);
console.log ("SCELTA" + scelta);
$http.post(link, {giorno: data.giorno, ora: data.ora, mail: mail, scelta: scelta})
.then(function (res){
console.log("Dentro http.post");
var response = res.data;
if (response != 'F'){
console.log("Dentro if");
console.log(response);
//window.location.href ="/#/main";
} else {
console.log("Dentro else");
}
});
};
}
dataService.$inject = ['$http'];
function dataService($http) {
console.log("qua");
var service = {
getEvents: getEvents
};
return service;
function getEvents() {
console.log("qua2");
var config = {
transformResponse: function (data, headers) {
var result = {
events: [],
schedules: []
};
var events = JSON.parse(data);
var dates = [];
console.log("qua3");
for (var i = 0; i < events.length; i++) {
if (dates.indexOf(events[i].day) === -1) {
var date = events[i].day;
dates.push(date);
result.events.push({
date: date
});
}
result.schedules.push({
date: events[i].day,
time: events[i].time
});
}
console.log("result: " + result);
return result;
}
};
return $http.get('http://localhost/ShuttleFIX/api/apiTimes.php', config)
.then(getEventsCompleted)
.catch(getEventsFailed);
function getEventsCompleted(response) {
console.log("response " + response.data);
return response.data;
}
function getEventsFailed(error) {
console.error(error);
}
}
}
is it possible to rewrite this code in a controller function without using factory?
Thank's

Making Sync calls using promises Angular JS factories

I am trying to make sync calls using a factory pattern.
$scope.doLogin = function (username, password, rememberme) {
appKeyService.makeCall().then(function (data) {
// data = JSON.stringify(data);
debugAlert("login controller app key service"+data);
var appkeyvalue = data.d.appkey;
sessionConfigurationService.setBasicToken(appkeyvalue);
loginService.makeCall(username, password, rememberme).then(function (accessTokenData) {
if (accessTokenData.access_token !== "")
{
sessionConfigurationService.setAccessTokenData(accessTokenData.access_token);
userPreferencesService.makeCall().then(function (userPreferencesData) {
if (userPreferencesData.d.userId !== "")
{
sessionConfigurationService.setUserPreferences(userPreferencesData.d);
// $window.location.href = '/base.html';
}
});
}
});
});
};
My appKeyService factory is
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function () {
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});
My authenticated service factory is
app.factory('authenticatedServiceFactory', function ($http, $q, sessionConfigurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function (methodType, URL, data, authType) {
var headerValue = "";
if (authType === "Basic") {
headerValue = sessionConfigurationService.getBasicToken();
} else if (authType === "Bearer") {
headerValue = sessionConfigurationService.getBearerToken();
}
var config = {headers: {
'Authorization': headerValue,
'Accept': 'application/json;odata=verbose',
},
withCredentials: true,
async: false
};
if (methodType === "GET") {
$http.get(URL, data, config)
.then(function (getData) {
debugAlert("GET method response" + JSON.stringify(getData));
deffered.resolve(getData.data);
}, function (error) {
debugAlert("GET method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "POST") {
$http.post(URL, data, config)
.then(function (putData) {
debugAlert("POST method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("POST method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "DELETE") {
$http.delete(URL, data, config)
.then(function (deleteData) {
debugAlert("DELETE method response" + JSON.stringify(deleteData));
deffered.resolve(deleteData.data);
}, function (error) {
debugAlert("DELETE method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "PUT") {
$http.put(URL, config)
.then(function (putData) {
debugAlert("PUT method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("PUT method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
return deffered.promise;
};
return service;
});
But I don't see the service calls are made in sync. So the "then" part in the controller is not executing after we receive the response. Its executing one after the other. How can I make that happen.
#Frane Poljak
Thank you for your comment. I just brought
var deffered = $q.defer();
inside the makeCall method and its working as I wanted now. Thank you!
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var service = {};
service.makeCall = function () {
var deffered = $q.defer();
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});

Javascript promise not executing in desired order

I have been trying to execute a number of tests for an API, for this example it required my account details to be updated. When I run the test the retrieveAccount call is sometimes run before my putRequest making the tests fail. What am I doing wrong?
var frisby = require('frisby');
var url = require('endpoints.js');
var auth = require('auth.js');
var oracledb = require('oracledb');
var dbConnect = require('dbconfig.js');
var myDetails = undefined;
var putRequest = function() {
frisby.create('Put update contact details - required values')
.put(url.myAccount, {
addressLine1: 'String',
addressTown: 'String',
addressCounty: 'String'
}, {json: true})
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.auth(auth.username, auth.password)
.toss();
}
var retrieveAccount = function() {
oracledb.getConnection(
{
user : dbConnect.user,
password : dbConnect.password,
connectString : dbConnect.connectString
},
function(err, connection)
{
if (err) {
console.error(err.message);
return;
}
connection.execute(
"SELECT addressLine1, addressTown, addressCounty "
+ "FROM accounts "
+ "WHERE account_id = 1",
function(err, result)
{
if (err) {
console.error(err.message);
return;
}
myDetails = JSON.stringify(result.rows);
myDetails = JSON.parse(myDetails);
});
});
}
var matchValues = function() {
frisby.create('Match Database and API Values')
.get(url.myAccount)
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.auth(auth.username1, auth.password1)
.afterJSON(function (body) {
expect(body.addressLine1).toMatch(myDetails[0][0])
expect(body.addressCounty).toMatch(myDetails[0][1])
expect(body.addressTown).toMatch(myDetails[0][0])
})
.toss();
}
function Promise(fn) {
var state = 'pending';
var value;
var deferred = null;
function resolve(newValue) {
value = newValue;
state = 'resolved';
if(deferred) {
handle(deferred);
}
}
function handle(handler) {
if(state === 'pending') {
deferred = handler;
return;
}
if(!handler.onResolved) {
handler.resolve(value);
return;
}
var ret = handler.onResolved(value);
handler.resolve(ret);
}
this.then = function(onResolved) {
return new Promise(function(resolve) {
handle({
onResolved: onResolved,
resolve: resolve
});
});
};
fn(resolve);
}
function sendRequest() {
return new Promise(function(resolve){
var value = putRequest();
resolve(value);
});
}
function readDatabase() {
return new Promise(function(resolve){
var value = retrieveAccount();
resolve(value);
});
}
function getAccount() {
return new Promise(function(resolve){
var value = matchValues();
resolve(value);
});
}
sendRequest()
.then(readDatabase)
.then(getAccount);
I recommend using sequenty instead of promises to execute synchronous REST calls.
sudo npm install sequenty
var sequenty = require('sequenty');
function f1(cb) // cb: callback by sequenty
{
frisby.create('Match Database and API Values')
.get(url.myAccount)
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.auth(auth.username1, auth.password1)
.afterJSON(function (body) {
expect(body.addressLine1).toMatch(myDetails[0][0])
expect(body.addressCounty).toMatch(myDetails[0][1])
expect(body.addressTown).toMatch(myDetails[0][0])
cb();
})
.toss();
}
function f2(cb)
{
frisby.create('Put update contact details - required values')
.put(url.myAccount, {
addressLine1: 'String',
addressTown: 'String',
addressCounty: 'String'
}, {json: true})
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.auth(auth.username, auth.password)
.toss();
}
sequenty.run([f1, f2]);

Categories