How return value from the function-CodeceptJS - javascript

I need to get a value from excel file when status column value is “Y” and I wanted to return the value from Name Column to the calling function and excel sheet contains the data is as follows
Name Number status
YYYY 1234 N
XXXXX 3456 Y
Function I have written like this
var Excel = require(‘exceljs’);
var workbook = new Excel.Workbook();
var selectStatus = ’’;
module.exports = function() {
return actor({
trimSelectName: function() {
workbook.xlsx.readFile("E:/testData.xlsx")
.then(function(sheetName) {
// use workbook
i = 1;
try {
var workSheet = workbook.getWorksheet("trim");
workSheet.eachRow({
includeEmpty: false
}, function(row, rowNumber) {
if (i == 1) {
i = 0;
} else {
currRow = workSheet.getRow(rowNumber);
console.log("Name :" + currRow.getCell(1).value + ", Number :" + currRow.getCell(2).value +
"Select Status :" + currRow.getCell(3).value);
selectStatus = currRow.getCell(3).value;
if (selectStatus == "Y") {
return selectStatus;
}
}
});
} catch (Error) {
console.log(Error);
}
});
},
});
};
But I am trying to the print value from the calling function, I am always getting it as undefined
Calling function:
const selected = trimDataSelection.trimSelectName();
Could you please let me know where could be the issue?

As I see your function returns actor object, I assume you are using steps_file generated by codeceptjs which is used to extend "I" object in order to add your custom functions. So if you want to invoke your custom function from scenario you should call it like this: const selected = I.trimSelectName()

Related

Get multiple values with local storage

I'd like to retrieve the name and the date of created tasks. I managed to put the value taskMessage in local storage, but I don't know how to add taskName as well. This is the code I currently have :
$(document).ready(function () {
var i = 0;
for (i = 0; i < localStorage.length; i++) {
var taskID = "task-" + i;
$('.task-container').append("<li class='item-content' id='" + taskID + "'>" + localStorage.getItem(taskID) + "</li>");
}
$('.floating-button').on('click', function () {
myApp.prompt('', 'Add Task', function (task) {
if (task !== "") {
myApp.prompt('', 'Choose time', function (time) {
var d1 = new Date();
d1.setHours(time, 0, 0, 0);
var hour = d1.getHours();
if (time > 0 && time < 25) {
var d2 = new Date();
var currenttime = d2.getHours();
if (time > currenttime) {
var taskID = "task-" + i;
var taskMessage = hour;
var taskName = task;
localStorage.setItem(taskID, taskMessage);
var newtask = '<li class="item-content ' + taskID + '"><div class="item-inner"><div class="item-title" >' + taskName + '</div><div class="item-after"> ' + taskMessage + ':00</div> </div></li>';
var taskitem = $('#' + taskID);
$('.task-container').append(newtask);
}
else {
myApp.addNotification({
message: 'Please choose a valide time period'
});
}
}
else {
myApp.addNotification({
message: 'Please choose a value between 1 and 24'
});
}
});
}
else {
myApp.addNotification({
message: 'Please enter a valid name'
});
}
});
});
});
First you should get the data into a variable
var getData =
{
"firstData":"data1",
"secondData":"data2",
"thirdData": "data3"
}
Then you can set the above data's in localStorage...
localStorage.setItem('dataKey', JSON.stringify(getData ));
Then get....
var val = localStorage.getItem('dataKey');
Enjoy!!!
If you want to store two different values in localStorage then you can do somrthing like this :
setItem in localStorage two times with different keys.
localStorage.setItem("message", taskMessage);
localStorage.setItem("name", taskName);
Store both the values in an object.
var obj = {
"message": taskMessage,
"name": taskName
}
var val = localStorage.setItem("task", obj);
typeof val: string
Value of val: [object Object]
setItem method convert the input to a string before storing it.
Try this :
// Put the object into storage
localStorage.setItem('task', JSON.stringify(obj));
// Retrieve the object from storage
var val = localStorage.getItem('obj');
console.log('retrievedValue: ', JSON.parse(val));
You can easily store values in localstorage using following example.
//Save the values to Localstorage
localStorage.setItem('first','firstvalue');
localStorage.setItem('second','secondvalue');
//Retrieve the values from localstorage
localStorage.getItem('first')
//"firstvalue"
localStorage.getItem('second')
//"secondvalue"
localStorage saves item key&value as string,so you call setItem with an object/json object,you must serialize json to string by JSON.stringify() method.when you get value you need parse string as json object using JSON.parse() method.
Test
test(`can't retrieve json from localStorage if raw json data saved`, () => {
localStorage.setItem('foo', {foo: 'bar'});
expect(localStorage.getItem('foo')).toEqual('[object Object]');
});
test(`retrieve json value as string from localStorage`, () => {
localStorage.setItem('foo', JSON.stringify({foo: 'bar'}));
let json = JSON.parse(localStorage.getItem('foo'));
expect(json.foo).toEqual('bar');
});
test(`key also be serialized`, () => {
localStorage.setItem({foo: 'bar'}, 'value');
expect(localStorage.getItem('[object Object]')).toEqual('value');
});
test('supports bracket access notation `[]`', () => {
localStorage.setItem('foo', 'bar');
expect(localStorage['foo']).toEqual('bar');
});
test('supports dot accessor notation `.`', () => {
localStorage.setItem('foo', 'bar');
expect(localStorage.foo).toEqual('bar');
});

Parse server save data in series

So we have large data in JSON format.
We want to save it to a class (table) in our Parse app.
I wrote a JS script which can read the file and go through the JSON data.
But when is do the saving it all gets messed up. Its loops in the first one for ever. I understand that there is something called promise bt I don't understand how to use it? Can anyone help. My code is given below.
function processJson(result) {
object = JSON.parse(result);
verbose.textContent = "Read " + object.results.length + " objects";
var count = object.results.length;
var countAc = 0;
logger("To save: " + count);
i = 0;
while (i < count) {
if (object.results[i].areaType == 'ac') {
save(i).then(function (object) {
i = i + 1;
logger("Success: " + object.id);
});
} else {
logger("ac not found");
i = i + 1;
}
}
}
function save(i) {
logger("ac found");
var constituency = new Constituency();
constituency.set("points", object.results[i].points);
constituency.set("areaType", object.results[i].areaType);
constituency.set("name", object.results[i].name);
constituency.set("state", object.results[i].state);
constituency.set("index", object.results[i].index);
constituency.set("pc", object.results[i].pc);
constituency.set("center", object.results[i].center);
constituency.set("oldObjectId", object.results[i].objectId);
return constituency.save();
/*constituency.save().then(function(obj) {
// the object was saved successfully.
i = i + 1;
logger("Success: " + obj.id);
}, function(error) {
// the save failed.
logger(error.message);
i = i + 1;
});*/
}
I would do something like that:
function processJson(result) {
var object = JSON.parse(result);
for (var i = 0; i < object.results.legnth; i++){
var parseObject = createParseObjectFromJSONObject(object.results[i]);
parseObject.save(null).then(function(object){
console.log("object saved: " + object.id);
},function(error){
console.log("error: " + error);
});
}
}
function createParseObjectFromJSONObject(jsonObject){
var constituency = new Constituency();
constituency.set("points", jsonObject.points);
constituency.set("areaType", jsonObject.areaType);
constituency.set("name", jsonObject.name);
constituency.set("state", jsonObject.state);
constituency.set("index", jsonObject.index);
constituency.set("pc", jsonObject.pc);
constituency.set("center", jsonObject.center);
constituency.set("oldObjectId", jsonObject.objectId);
return constituency;
}
You can do it even better..
You can first push all the parse objects into array and then call saveAll to save all the parse objects in one request. This solution is good for < 1000 records .. if you have more than 1000 then you can do paging (first 1000 and saveAll, other 1000 and saveAll ....)
In this version your code will look like this:
function processJson(result) {
var object = JSON.parse(result);
var allObjects = [];
for (var i = 0; i < object.results.legnth; i++){
var parseObject = createParseObjectFromJSONObject(object.results[i]);
allObjects.push(parseObject);
}
// outside the loop we are ready to save all the objects in
// allObjects array in one service call!
if (allObjects.length > 0){
Parse.Object.saveAll(allObjects).then(function(){
console.log("all objects were saved!");
// all object ids are now available under the allObjects array..
},function(error){
console.log("error: " + error);
});
}
}
function createParseObjectFromJSONObject(jsonObject){
var constituency = new Constituency();
constituency.set("points", jsonObject.points);
constituency.set("areaType", jsonObject.areaType);
constituency.set("name", jsonObject.name);
constituency.set("state", jsonObject.state);
constituency.set("index", jsonObject.index);
constituency.set("pc", jsonObject.pc);
constituency.set("center", jsonObject.center);
constituency.set("oldObjectId", jsonObject.objectId);
return constituency;
}
Good Luck :)

Return spreadsheet values to javascript

I'm quite annoyed by a problem with google script and javascript.
I have a problem to send datarange values from my google script to be treated by my javascript function.
Here is my code.
code.gs extract:
function getSheetData(ss,sh){
// Create sheet object
var ass = SpreadsheetApp.openById(ss);
SpreadsheetApp.setActiveSpreadsheet(ass);
var ash = SpreadsheetApp.openById(ss).getSheetByName(sh);
ash = SpreadsheetApp.getActive();
var result = ash.getDataRange().getValues();
Logger.log("getSheetData(ss,sh) result : "+result);
// return result after JSON strinfigy
return JSON.stringify(result);
}
JavaScript.html extract :
function readTb(fn) {
var result = google.script.run.getSheetData(bdData, tbData);
console.dir('readTb result : ' + result);
fn(result);
}
function buildSelect(range) {
console.log('Range = ');
console.dir(range);
if (range.length > 0) {
buildOption('', 'Choose an order');
for (i = 0; i < range.length; i++) {
var row = range[i];
buildOption(row[0], row[0] + " ~ " + row[2] + " ~ " + row[5]
+ " ~ " + row[7]);
}
} else {
buildOption('', 'No order to display');
}
}
function buildOption(data) {
console.log(data);
}
/**
/* Retrieve orders and format to fill select numCommande input
/*
*/
function listCommandesPesee() {
console.log('Call for orders seeking');
// Read DB and retrieve data
// feed function variables with CONST
bdData = BDDATA_OLD;
tbData = TBCOMMANDES;
// Call readTb to retrieve data, then buildSelect to format result
var promise1 = new Promise(readTb);
promise1.then(buildSelect);
console.dir(promise1);
}
By now, Logger.log in GS IDE shows right data:
[16-07-27 08:01:22:040 PDT] résultat de getSheetData(ss,sh) : Ligne,ID,Produit,Date,Fournisseur,Numéro Camion,Silo,Cellule,Ilot,Poids coop,Poids net livré,N° analyse qualité,Cellule destination ,Transport
...
on page load, listCommandesPesee is called, which call readTb().
But even with json stringify, I still have an undefined value in var result (readTb function) and so range in buildSelect doesn't have any length property.
JSON.Stringify was working when I was testing and before I add promise and chain (I do think)
Because I'm stuck on this. I'll be grateful for any help.
Thanks
The return from the server, can not be received by the same function that is using google.script.run.
Currently:
function readTb(fn) {
var result = google.script.run.getSheetData(bdData, tbData);
console.dir('Résultat de lecture des données : ' + result);
fn(result);
}
Should Be:
function readTb() {
var result = google.script.run
.withSuccessHandler(mySuccessFnc)
.getSheetData(bdData, tbData);
}
function mySuccessFnc(resultReturned) {
console.dir('Résultat de lecture des données : ' + resultReturned);
};

BarcodeScanner2 = TypeError: Cannot set property 'innerHTML' of null

I am trying to develop a barcode scanning app using phonegap-1.4.1 in android. I am trying to store all the values in an array code[] and later on I am displaying the values using the array. I am creating a local storage of the values. Here is my declaration of an array and a counter.
localStorage["counter"]=0;
var code = ["Test1", "Test2","Test3", "Test4"];
localStorage.setItem("code", JSON.stringify(code));
Here is my javascript file for scanning the barcode and I am using an recursive function in this so that the app scanning continues and the values are stored in the array.
var scanCode = function () {
window.plugins.barcodeScanner.scan(
function (result) {
if(result.cancelled == true ) {
window.location.href = 'page5.html';
} else {
var test2 = JSON.parse(localStorage.getItem("code"));
var k = parseInt(localStorage.getItem("counter"));
document.getElementById(test2[k]).innerHTML = "result.text";
k++;
localStorage["counter"] = k;
alert("Scanned Code: " + result.text + ". Format: " + result.format + ". Cancelled: " + result.cancelled);
scanCode();}
}, function (error) {
alert("Scan failed: " + error);
window.location.href = 'page5.html';
});
}
And after storing the values I am displaying the values in some page5.html as
<tr>
<td >1</td>
<td>
<p id="Test1"></p></td>
</tr>
But I am getting the error as BarcodeScanner2 = TypeError: Cannot set property 'innerHTML' of null. Somebody please help me on this issue. Thanks in advance.
Add below javascript Function in your html file ( top of the page).
function SaveDataToLocalStorage(barcodeValue)
{
var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];
var newItem = {
'barcode': barcodeValue
};
oldItems.push(newItem);
localStorage.setItem('barcodes', JSON.stringify(oldItems));
}
Now Change Your barcode Scan Code as below :
var scanCode = function () {
window.plugins.barcodeScanner.scan(function (result) {
if(result.cancelled == true ) {
window.location.href = 'page5.html';
} else {
// below function save your data in localstorage.
SaveDataToLocalStorage(result.text);
scanCode();
}
}, function (error) {
alert("Scan failed: " + error);
window.location.href = 'page5.html';
});
}
Now, if you want to display all barcodes in page5.html just read all barcodes from localstorage and display it in page.
use following function page5.html to display all barcodes in page5.html
function displayValues()
{
var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];
for(var i=oldItems.length-1;i>=0;i--)
{
var html=document.getElementById("allCodes").innerHTML;
document.getElementById("allCodes").innerHTML=html+"<br>"+oldItems[i].barcode;
}
}
make one div name allCodes in page5.html
Your page5.html
<body>
<div id="allCodes">
</div>
</body>
<script>
function displayValues()
{
var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];
for(var i=oldItems.length-1;i>=0;i--)
{
var html=document.getElementById("allCodes").innerHTML;
document.getElementById("allCodes").innerHTML=html+"<br>"+oldItems[i].barcode;
}
}
displayValues();
</script>
//Display in table :
function displayValues()
{
var oldItems = JSON.parse(localStorage.getItem('barcodes')) || [];
if(oldItems.length>0)
{
document.getElementById("allCodes").innerHTML="<table border='2'>";
}
for(var i=oldItems.length-1;i>=0;i--)
{
var html=document.getElementById("allCodes").innerHTML;
html=html+"<tr><td>"+oldItems[i].barcode+"</td></tr>";
document.getElementById("allCodes").innerHTML=html;
}
if(oldItems.length>0)
{
var old=document.getElementById("allCodes").innerHTML;
document.getElementById("allCodes").innerHTML=old+"</table>"
}
}
The error is clearly related to document.getElementById(test2[k]) returning no element, hence, there is no element with the id given. In your sample this would be Test1.
Set the id of the paragraph to Test1 instead of Text and it find the element.

Windows 8 Application Javascript and SQlite (Database is locked)

I write some simple app for windows 8 Metro UI with javascript. Because natural method from microsoft to use Sqlite with Javascript in Metro UI. I use 'doo' wrapper:
dooWrapper SQLite (github)
I create a method :
function addSomething(name) {
var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\a_db.sqlite';
SQLite3JS.openAsync(dbPath).then(function (db) {
return db.runAsync("INSERT INTO STH (nazwa) VALUES (:name)", { name: name }).
done(function () {
console.log('Add sth : ' + name);
db.close();
}, function (error) {
if (db) {
db.close();
}
console.log('ERROR Adding sth' + error.message);
})
});
}
I get error 'database is locked' I read about this error in documentation. But I have one question is other solution to add more rows without create 'insert' function with collections argument something like that : insert (array) ? I just want to use that function n-times without this error. That's possible?
Yes,it possible...i also got this error before....For that you just need to establish the database connection once...i have used this in my app and its working fine.
If there is no need of closing your db then then open database once like..
Add this code to default.js file
var myDatabase; //Global Variable
var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\db.sqlite';
//Create Table
SQLite3JS.openAsync(dbPath).then(function(db) {
myDatabase=db;
return db.runAsync('CREATE TABLE Item (name TEXT, price REAL, id INT PRIMARY KEY)');
});
Then you just need to use below code
// For Insert
return myDatabase.runAsync('INSERT INTO Item (name, price, id) VALUES ("'+ array[i].name+'", "48484", 1);
For array
var dbPromises = [];
var testArray = [];
//only for test purpose
//You can pass your array here directly
for (var a = 0; a < 300; a++) {
var obj = {
name: "Mango"+a,
price: 100+a,
id: a
};
testArray.push(obj);
}
for (var i = 0; i < testArray.length; i++) {
var query = 'INSERT OR REPLACE INTO Item (name, price, id) VALUES ("' + testArray[i].name + '",' + testArray[i].price + ',' + testArray[i].id + ')';
dbPromises.push(globalDatabase.allAsync(query));
}
WinJS.Promise.join(dbPromises).then(function () {
debugger;
}, function(err) {
debugger;
});
Above code is used only for less array size...bcz its taking too much time for insertion...
For fasst execution you should replace just below code
for (var i = 0; i < testArray.length; i++) {
var val = '("' + testArray[i].name + '",' + testArray[i].price + ',' + testArray[i].id + '),';
query = query + val;
if ((i + 1) % 300 == 0 || (i + 1) == testArray.length) {
query = query.replace(/,$/, "");
dbPromises.push(globalDatabase.allAsync(query));
query = 'INSERT OR REPLACE INTO Item (name, price, id) VALUES ';
}
}

Categories