how to make function calls synchronously inside evaluate? - node.js

Hi Am doing an automation using PhantomJS combined with nightmare, I need to make a DB call once my UI automation via nightmare is executed am making use of the evaluate function of nightmare to make the DB call what i expected was that the call will be made synchronously but what actually happens is that my DB function is triggered first before the UI automation execution gets completed as a result am passing incorrect data for DB verification .
Below is a sample of ma code
exports.rejectProcess = function (testData, resultfolder, ConnectionStrings) {
"use strict";
return function (nightmare) {
nightmare
.waitForEnable('#Process')
.click('#Process')
.wait()
.waitForNotVisible('div.spinnerFullLight')
.waitForEnable('#createProcess')
.click('#createProcess')
.wait()
.click('#ContinueBtn')
.wait()
....etc
.evaluate(
function ()
{
var element = document.querySelector('#ProcessNumber');
return { data: element.value }
},
function (result) {
nightmare
.waitForEnable("#spanDashBoardArrowd")
.click("#spanDashBoardArrowd")
.waitForVisible("#topNavdropdownSubMenu")
.click("#navApprovals")
.wait()
...etc
.click("#Reject")
.evaluate(function () { nightmare.wait(60000);},valuateDB(testData, ConnectionStrings, result.data))
})
}
};
function valuateDB(testData, ConnectionStrings,concessionNumber)
{
console.log(concessionNumber);
var ApprovalInfo = dataOperation.getRejectStatus(testData, ConnectionStrings, concessionNumber); ------->place where i make the DB call
console.log(ApprovalInfo);
}

Related

NodeJS Unit test how to spy/stub

I am stuck on this for few days now.
while testing my handler function I would like to "fake" the call to rotateApiKeys fonction I was thinking to use stubs to achieve that.
But first I would like to see if at least I could spy on rotateApiKeys while calling the handler, so far I am getting:
AssertError: expected rotateApiKeys to be called once but was called 0 times and I can see that function actually been called.
Questions:
What would you recommend me to use? Mock/Stub/Spy
If Spy should work, why I am getting that assertError?
Handler:
async function handler(event) {
// declare a new JSON object
let handlerObject = {
"event": event,
"isValidEvent": rotateFunctions.validateEvent(event),
"actionCountObject": {}
};
if (handlerObject.isValidEvent) {
// continue here
handlerObject.actionCountObject = await rotateApiKeys(event);
}
// console log JSON handlerObject
console.log("handlerObject: " + JSON.stringify(handlerObject));
// return the object
return handlerObject;
}
unit test code:
it("Should call rotate", async function() {
var rotate = sinon.spy(rotateApiKeys, 'rotateApiKeys');
const result = await rotateApiKeys.handler(event);
rotate.restore();
sinon.assert.calledOnce(rotate);
});

How to do callback in our component using react jest test cases

How can we do callback on success and failue cases for below lines of code for test coverage using jest
const handleService = () => {
window.domain.service("1321",'',onSuccess, onFailure)
}
const onSuccess = () => {
....update state values
}
const onFailure = () => {
....update state values
}
Something like this:
Spy on window.domain.service to gain access to the calls it receives. This will allow you to access the parameters of those calls which will be "1321",'',onSuccess, onFailure
Assign the function you wish to test to a variable
Invoke the function to execute the code in it (this will get you the coverage)
(Optional) assert that the callback functions behave correctly
Here is a snippet to help demonstrate
it('should run', () => {
// Some setup to create the function on the window, may not be needed if done elsewhere.
// Could be good to do this in a beforeEach and clean up in afterEach to avoid contaminating the window object
window.domain = {
service: () => {},
}
// Spy on the window.domain.service method.
// Provide a mock implementation if you don't want the real one to be called
const serviceSpy = jest.spyOn(window.domain, 'service');
executeYourCode();
// capture the arguments to the call
const [_arg1, _arg2, onSuccess, onFailure] = serviceSpy.mock.calls[0];
// execute the callbacks
onSuccess();
onFailure();
});

Capture Total Time or duration of a Test Suite using Jasmine Hook

I have been trying to retrieve 'totalTime' from the jasmineDone hook or 'duration' from SuiteResult as documented at [https://jasmine.github.io/api/edge/global.html#] but they don't seem to be available. Would be grateful for any pointers?
I found #DublinDev answer to this Jasmine get current test result which was so helpful. This allows me to get the duration per test using the specDone hook which I could potentially use and add each result, but I am curious to know if I am doing something wrong.
I am using the following code from the link above( 2nd link) and would expect either of the console.logs to output a time but neither are outputting anything
function dbReporter() {
this.jasmineStarted = function (options) { };
this.specStarted = function (result) { };
this.specDone = async function (result) { };
this.suiteStarted = function (result) { };
this.suiteDone = function (result) {
console.log('duration=', result.duration)
}
this.jasmineDone = async function (result) {
console.log('totalTime=', result.totalTime)
}
}
module.exports = dbReporter;
Given that you have the latest version of Jasmine already I would recommend just making your own timer which starts in jasmineStarted hook and ends in JasmineDone hook.
onPrepare: () => {
//Create a global variable to be used for the timer
global.jasmineTimer = 0;
jasmine.getEnv().addReporter({
jasmineStarted: function (options) {
jasmineTimer = Date.now();
console.log(`Starting execution ${jasmineTimer}`)
},
jasmineDone: async function (result) {
console.log(`Finished execution in ${(Date.now() - jasmineTimer) / 1000}s`)
}
})
}

Firestore onWrite trigger using callback return undefined

i tried to add a trigger function on my cloud functions.
When a document changed i want to perform some work. I have already the code for the work to do in another file (i separate my work into files, so it's get easier for me), so i have a function that performs work and when it is finished the callback is called.
This is what my index.js look like:
// requires...
// Express, i also use express for simulating an API
const app = express()
// So there is my Listener
const listenerForChange = functions.firestore
.document('myPath/documentName')
.onWrite((change, context) => {
const document = change.after.exists ? change.after.data() : null;
if (document != null) {
const oldDocument = change.before.data();
const newDocument = change.after.data()
// Here i call my function that is in the worker-listeners.js
listenerWorker.performStuff(newDocument, function() {
return 0
})
}
else {
console.error("Listener for classic was triggered but doc does not exist")
return 0
}
});
const api = functions.https.onRequest(app)
module.exports = {
api,
listenerForChange
}
...
There is my listenerWorker.js :
module.exports = {
performStuff: function(data, complete) {
performStuff(data, complete)
}
};
function performStuff(data, complete) {
// do stuff here ...
complete()
}
Problem is that i always an error in the Firebase console saying : Function returned undefined, expected Promise or value
Even if i do not do anything inside my worker and calling the callback as soon as i can i get the error.
So i understand the functions needs a response, promise or value. But it's like i'm not in the scope anymore but i do not want to return before the work is finished !
Any help ? thank you guys
All asynchronous work that you perform should be represented by a promise. If you have a utility object that does async work, it should return a promise so that the caller can decide what to do next with it. Right now you're just using callbacks, and that's going to make things much more difficult than necessary (because you'll have to "promisify" those callbacks).
Just use promises everywhere and it'll be much more clear how your function should work.

NodeJS callback is calling too early

I am running the following two functions one after the other. When runScript() finishes the callback function should be triggered. However these functions are running asynchronously, and data from the first function (which is required for the second function) returns as undefined.
I am new to callback functions, and am possibly approaching this incorrectly. I've omitted insertAssets() and insertPairs() for clarity, but their code is asynchronous and involves DB calls.
function runScript(cb) {
for(var name in exchange_objects) {
insertAssets(exchange_objects[name].assets, name); // runs some async code
}
cb();
}
runScript(function() {
for(var name in exchange_objects) {
insertPairs(exchange_objects[name].pairs, name); // runs some async code
};
});

Resources