How to run a node async function locally? - node.js

I'm attempting to write a Node async function and run test it locally. I have this function (using nano for CouchDB):
async function calldb() {
console.log("entering calldb")
const q = {
... query def ...
};
try {
console.log("before await")
const response = await nano.db.find(q)
console.log("after await")
} catch (e) {
return { Error: e}
}
console.log(response);
return response;
}
I want to test locally, so I'm doing npx run-func getGoods.js calldb. This yields:
npx run-func index.js calldb
npx: installed 1 in 0.91s
entering calldb
before await
The first console log runs, but then it doesn't wait around for the response from the db.
How can I test this locally to see if I am actually connecting to the Couch database? How can I get the return from the db call to log to console?

If you look at the code of the library that you indicate (https://github.com/DVLP/run-func/blob/master/index.js), it does not wait for an async function.
If you want to use that library you would need to change the code.

Related

Can I execute a function in response to a failed assert in TestCafe?

We are using Testcafe for our regression tests and I would like to enhance the test logging of failed asserts by adding any messages from the browser console to the output. According to the Testcafe documentation, this code will print "The test has failed" in case the given element is not visible on the page:
await t.expect(Selector('#elementId').visible).ok("The test has failed");
According to the doco, the browser console messages can be read using the the t.getBrowserConsoleMessages method, but I have not been able to combine them into one statement like e.g.
await t.expect(Selector('#elementId').visible).ok(console.log(await t.getBrowserConsoleMessages()));
as this always processes the getBrowserConsoleMessages method and outputs the console messages, regardless of whether the assert is successful or not.
Is there a way to make this work only if the assert fails?
I seems you just need to call getBrowserConsoleMessages conditionally.
To get the expected behavior, you can use the following code:
import { Selector } from 'testcafe';
fixture`A set of examples that illustrate how to use TestCafe API`
.page`http://devexpress.github.io/testcafe/example/`;
test('Test1', async t => {
const isVisible = await Selector('#developer-name').visible;
if (!isVisible)
console.log(await t.getBrowserConsoleMessages())
await t.expect(isVisible).ok();
});
test('Test2', async t => {
const isVisible = await Selector('#developer-name2').visible;
if (!isVisible)
console.log(await t.getBrowserConsoleMessages())
await t.expect(isVisible).ok();
});
Here is how I got this working myself:
import { Selector } from 'testcafe';
async function objToString (obj) {
return Object.entries(obj).reduce((str, [p, val]) => {
return `${str}${p}::${val}\n`;
}, '');
}
fixture('My test')
.page('https://myurl.com')
test('Test1', async t => {
....
await t.expect(Selector('#elementId').visible).ok(await objToString(await browser.getBrowserConsoleMessages()));
....
});

NodeJS Asyn/Await for build configuration with nodecloud-config-client

My NodeJS application is using spring cloud server for configurations and I am loading this at the application startup. I am using the below function to load config but I can see the promise status is pending and seems to be the call is still async. How can I make it as a sync call to wait until the configurations are loaded. Thanks in advance!
async function fetchConfig(){
await client.getConfig().then(conf => {
console.log(conf);
}).catch(console.error);
}
async/await is a way to replace promise based callback, but you use them at same time, you can change it to:
async function fetchConfig(){
try {
const conf = await client.getConfig();
console.log(conf);
} catch (ex) {
console.error(ex);
}
}

My nodejs code is being skipped on a Google Cloud Function

I have a node cloud function on GCP, which is working relatively fine, i even have a global logger and logs just to track the workflow, but now i'm having some strange issues with some calls to the cloud function.
async function updateCompletedRunInDB(runId, runObject, shouldChargeOrganization) {
log.info(runId + " - starting to update models");
const now = Date.now();
let run;
let chargeableMins;
let outputFileEntry, logFileEntry;
const runQuery = {
_id: runId,
};
// we load the run from the run model
run = await procLoadRun(runId);
and fucntion procLoadRun is something like this...
async function procLoadRun(runId) {
try {
run = await loadRun(runId);
} catch (err) {
log.error(err);
log.error("couldn't be loaded");
}
return run;
}
where loadRun is a query to mongodb that returns a specific run.
now on the gcp console i have the following (normal case scenario)
but sometimes i'm getting this one
Looks like my code is being skipped since procLoadRun is not being called, any ideas or suggestion would be appreciated.
my guess is something related to gcp? the cloud function is on nodejs10 with 1Gib memory
thanks in advance.

Calling http GET requests from ibm cloud functions using nodejs

while developing the cloud function I got the following error.
i created a cloud action and used that action name inside the json response in watson assistance. then once the intent is matched it call the cloud function. I selected nodejs as developing language of the cloud function.
now my real requirement is to call a https get request from that cloud function. for that i need to use nodejs library called node-rest-client.
normally we need to install it by typing "npm install node-rest-client" in the terminal. since there is no terminal in IBM nodejs editor i got, could you please let me know how to do that.
As a substitute i used https library which is already in nodejs package. and wrote the following code in the editor
const https = require('https');
function main() {
https.get('https://f6054382.ngrok.io/webhook/testRequest', (resp) => {
resp.on('data', (d) => {
process.stdout.write(d);
});
});
}
main();
once I type "node init" in local folder and add the above code to index.js file and then run it using the command "node index.js" code works successfully by giving me the expected output from the webservice.
But I do not get that result in IBM nodejs editor
https://console.bluemix.net/openwhisk/details/action/dialogif.psi%2540gmail.com_dev/webhookCall/code
once i save the above code and invoke by clicking the button in right upper i get the successes response in green as follows.
Activation ID:
341d4e5bc81f4e489d4e5bc81f2e4888
Results:
{}
Logs:
[]
could you please help me to sort this out
Thank you
When executing an asynchronous operation, e.g. HTTP request, you need to return a Promise from the action handler. This ensures the platform will block on that asynchronous result before completing the invocation.
function main() {
return new Promise((resolve, reject) => {
https.get('https://f6054382.ngrok.io/webhook/testRequest', (resp) => {
resp.on('data', (d) => {
process.stdout.write(d);
resolve({})
});
});
})
}
The underlying issue is that your code runs asynchronously and does not return a Promise to indicate a result will be available in the future.
I'd suggest to use the request-promises, which comes pre-packaged with OpenWhisk's Node.js runtime.
const request = require('request-promise');
function main(params) {
return request("https://f6054382.ngrok.io/webhook/testRequest").then(response => {
process.stdout.write(response);
});
}

Resemblejs in jest hangs

I'm using ResembleJS for image comparison. I can get it to run when I run it in a standalone script. Here's the code:
var compareImages = require('resemblejs/compareImages');
var fs = require('fs');
var path = require('path');
// The parameters can be Node Buffers
// data is the same as usual with an additional getBuffer() function
async function getDiff() {
var img = path.join(__dirname, 'small.jpg');
const data = await compareImages(
fs.readFileSync(img),
fs.readFileSync(img)
);
console.log(data);
fs.writeFileSync('./output.png', data.getBuffer());
}
getDiff();
Everything works as expected.
But when I run the comparison inside of a test in with the jest framework, it hangs and eventually times out. At first I thought maybe it was just running really slow, so I set my max timeout in jest to be 1 minute. Still failed. So I set my test image to be 1 pixel so it's the simplest test. Still wouldn't finish.
Running from a docker container with Node 8.9.4 (which is what comes from the docker hub node:8). Running jest 22.0.4.
Anybody else have issues running these two together?
I know Resemblejs runs tests with Jest, so not sure what could be causing the issue.
could you please post the code for your tests ?
Are you sure you are returning something from your test block ? In order for an test not to hang you need to return a promise which will resolve before the timeout. Below two examples
test("test", () => {
// test is done when writeFile resolves
return new Promise((resolve, reject) => {
fs.writeFile("path", "encoding", (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
test("test", async function () {
// test is done after the assertion
const result = await fetch();
expect(result).toBe(); // test;
});
I had a similar problem with slow tests with Jest, React and Docker (but I'm not using Resemblejs).
I found the solution on Github:
And for me solution was simply add "roots": ["./src"] to jest.config.js

Resources