Node.js application exits without throwing errors - javascript

I'm experiencing a weird issue with nodejs, my application quits without throwing any error or logging anything into the console. The whole code runs in a while (true) loop, I checked all of the if/else and try/catch blocks and the code never has a reason to stop, in fact this happens after running for some hours without any issue.
I've also tried adding a general error handler on the main function of the application like this:
try {
start()
} catch(err) {
utils.logMessage(`General Error: ${err}`, 'red')
utils.sendErrorWebhook(err)
}
It didn't change anything though, and when checking logs everything runs smooth and then suddenly stops.
Has anyone ever experienced this issue or know how to fix? Main modules I'm using are the mongodb official client (not mongoose) and axios.

Related

Selenium with nodejs- a process not stop even if the error comes, the issue facing on 107.XX version of chrome browser and chrome driver

I am working in NODE JS (javascript) with selenium webdriver.
Package.json-
“chai”: “^4.3.6”, “chromedriver”: “^107.0.3”, “geckodriver”: “^3.2.0”, “mocha”: “^10.0.0”, “mochawesome”: “^7.1.3”, “moment”: “^2.29.4”, “selenium-webdriver”: “^4.5.0”, “selenium-standalone”: “^8.2.3"
file1.js
it("Test code", async function(){ console.log("START"); await driver.sleep(3000); console.log("HELLO); await driver.findElement(Xpath).sendKeys("TEXT"); console.log("STOP"); })
the problem has been coming when updating the chrome driver or chrome browser, the issue is when the old code runs and when it doesn't. So is there any problem with this latest version or what?.
EX. I want to run my code like by like TOP to Bottom, which means first run the first line then after next so on, so I am put await driver.sleep(3000), which means the process hold at least 3 sec then after running next step, here before update the version it's working as expected but now some time its work and sometimes not, also not getting an error if found any error during runtime, currently process shows continues ongoing. Even if we put timeout then also not stop after time reach,
if remove the "await" command then do not run sync mode.
really confused what's going on. not getting errors and the process taking more and more time means not stopping automatically.
It may not fix your problem, but you will need to make sure that you have quotes around the word 'Hello' when you are trying to console.log it.
console.log("HELLO);
Should be:
console.log("HELLO");

Is there a way to capture js errors but not fail testcafe tests because of them?

I'm currently starting to write some TestCafe tests, and came across an issue in our website whilst running them - a JS error in the console fails the test. Naturally, I was quite pleased that my test had caught this, but it would mean that even if a JS error happens that is low priority and affects no users directly, our tests may fail and prevent a build.
Now this may be a workflow some want, but for us we'd rather raise a ticket and address it in a parallel workflow rather than block everyone because of a JS error. I'm aware of the --skip-js-errors option, however this just throws away all the errors entirely. Is there a middle ground, like converting the errors to warnings, or simply adding some sort of after-test function that logs out any JS errors that occurred during the test run? I've tried adding an afterEach to my fixture like so:
.afterEach(async t => {
const { error } = await t.getBrowserConsoleMessages();
console.log(JSON.stringify(error));
});
But with --skip-js-errors this does nothing. I'd love some pointers on this please!
My goal, in case it wasn't clear - I want to see the possible JS errors in my TestCafe run so that I can log them and make tickets off them, but I don't want them to fail the test run.
TestCafe does not provide such functionality out of the box. As you correctly mentioned, the --skip-js-errors flag ignores all errors and does not log them.
However, you can achieve the desired functionality using the Script Injecting mechanism. Please refer to the following article for more details: https://devexpress.github.io/testcafe/documentation/using-testcafe/common-concepts/inject-scripts-into-tested-pages.html#inject-script-code
I recommend you continue using the --skip-js-errors flag and add a custom window.onerror handler. Please see the example:
fixture `fixture`
.page `../pages/index.html`;
test.clientScripts({
content: `
window.addEventListener('error', function (e) {
console.error(e.message);
});`
})(`Skip error but log it`, async t => {
console.log(await t.getBrowserConsoleMessages());
});
In this code, I add the error event handler. Inside the handler, I call the console.error method. In this case, t.getBrowserConsoleMessages will return the correct log of errors.
Please use this approach along with the --skip-js-error flag.
Thus, the command will be the following: testcafe chrome test.js --skip-js-errors.

How to ignore an error in Vanilla JavaScript

I am running a Tampermonkey script on a website that I do not have the code for.
Sometimes it happens that I have a value that does not exist on the page and I get the following error:
"Cannot read property 'click' of null"
And the entire script stops. How can I tell get my script to ignore the error and just carry on to the next line of code?
Here is an example of a vanilla Javascript line that I work with:
document.querySelector('[value="xyz"]').click();
Only execute click() if the selector found something:
if(document.querySelector('[value="xyz"]'))
document.querySelector('[value="xyz"]').click();
You can't, and you shouldn't want to: errors are bad. They're not informative, they are a signal that the code has run into an unrecoverable error and the current code path should be terminated. If you were to ignore it, and keep running, now you're in a state where any subsequent line is just as likely to also throw an error.
Either actually fix things, by making your tampermonkey script not interfere with the way the page it's running on builds its DOM, or as a last resort, you can find out which function is throwing the error for the specific page(s) you're running into this, and then _specifically for those pages, find and rebind the entire function using a try/catch, such as:
const _old_fn = window.theFunctionInvolved;
window.theFunctionInvolved = function(...args) {
try { return _old_fn(...args); }
catch (e) {}
};
But of course, all you've now done is moved the buck: you'll have effectively guaranteed different errors later on, with the actual cause now permanently hidden.
So really: don't do this. Fix your tampermonkey script, or stop using it altogether.

TestCafe Runner.run(runOptions) never returns, browser hangs (Firefox & Chrome)

I've got a little sandbox project I've been playing around with for the last few weeks to learn the in's and out's of implementing a TestCafe runner.
I've managed to solve all my problems except one and at this point I've tried everything I can think of.
Reviewed the following similar questions:
How to close testcafe runner
How to get the testCafe exit code
But still my problem remains.
I've toyed around with my argv.json file.
I've toyed around with my CICDtestBranches.json file.
I've toyed around with my package.json file.
I've tested the same branch that has the problem on multiple
machines.
I've tested with multiple browsers (Firefox & Chrome) -
both produce the same problem.
I've tried to re-arrange the code, see
below
I've tried add multiple tests in a fixture and added a page
navigation to each one.
I've tried to remove code that is processing
irrelevant options like video logs & concurrency (parallel execution)
I also talked with some coworkers around the office who have done similar projects and asked them what they did to fix the problem. I tried their recommendations, and even re-arranging things according to what they tried and still no joy.
I've read through the TestCafe documentation on how to implement a test runner several times and still I haven't been able to find any specific information about how to solve a problem with the browser not closing at the end of the test/fixture/script run.
I did find a few bugs that describe similar behavior, but all of those bugs have been fixed and the remaining bugs are specific to either Firefox or Safari. In my case the problem is with both Chrome & Firefox. I am running TestCafe 1.4.2. I don't want to file a bug with TestCafe unless it really is a confirmed bug and there is nothing else that can be done to solve it.
So I know others have had this same problem since my coworker said he faced the same problem with his implementation.
Since I know I am out of options at this point, I'm posting the question here in the hopes that someone will have a solution. Thank you for taking the time to look over my problem.
When executing the below code, after the return returnData; is executed, the .then statement is never executed so the TestCafe command and browser window are never terminated.
FYI the following code is CommonJS implemented with pure NodeJS NOT ES6 since this is the code that starts TestCafe (app.js) and not the script code.
...**Boiler Plate testcafe.createRunner() Code**...
console.log('Starting test');
var returnData = tcRunner.run(runOptions);
console.log('Done running tests');
return returnData;
})
.then(failed => {
console.log(`Test finished with ${failed} failures`);
exitCode = failed;
if (argv.upload) return upload(jsonReporterName);
else return 0;
testcafe.close();
process.exit(exitCode);
})
.then(() => {
console.log('Killing TestCafe');
testcafe.close();
process.exit(exitCode);
});
I've tried to swap around the two final .then statements to try and see if having one before the other will cause it to close. I copied the testcafe.close() and process.exit() and put them after the if-else statement in the then-failed block, although I know they might-should not get called because of the if-else return statements just before that.
I've tried moving those close and exit statements before the if-else returns just to see if that might solve it.
I know there are a lot of other factors that could play into this scenario, like I said I played around with the runOptions:
const runOptions = {
// Testcafe run options, see: https://devexpress.github.io/testcafe/documentation/using-testcafe/programming-interface/runner.html#run
skipJSErrors: true,
quarantineMode: true,
selectorTimeout: 50000,
assertionTimeout: 7000,
speed: 0.01
};
Best way I can say to access this problem and project and all of the code would be to clone the git lab repo:
> git clone "https://github.com/SethEden/CAFfeinated.git"
Then checkout the branch that I have been working this problem with: master
You will need to create an environment variable on your system to tell the framework what sub-path it should work with for the test site configuration system.
CAFFEINATED_TEST_SITE_NAME value: SethEden
You'll need to do a few other commands:
> npm install
> npm link
Then execute the command to run all the tests (just 1 for now)
> CAFfeinated
The output should look something like this:
$ CAFfeinated
Starting test
Done running tests
Running tests in:
- Chrome 76.0.3809 / Windows 10.0.0
LodPage
Got into the setup Test
Got to the end of the test1, see if it gets here and then the test is still running?
√ LodPage
At this point the browser will still be spinning, and the command line is still busy. You can see from the console output above that the "Done running tests" console log has been output and the test/fixture should be done since the "Got to the end of the test1,..." console log has also been executed, that is run as part of the test.after(...). So the next thing to execute should be in the app.js with the .then(()) call.....but it's not. What gives? Any ideas?
I'm looking for what specifically will solve this problem, not just so that I can solve it, but so others don't run into the same pitfall in the future. There must be some magic sauce that I am missing that is probably very obvious to others, but not so obvious to me or others who are relatively new to JavaScript & NodeJS & ES6 & TestCafe.
The problem occurs because you specified the wrong value for the runner.src() method.
The cause of the issue is in your custom reporter. I removed your reporter and now it works correctly. Please try this approach and recheck your reporter.

how to force js ignore uncaught error and continue to work?

When run javascript app integrating with some 3rd party library, in some cases , 3rd party lib will lead to bug , for example, following typical error:
Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
The above error is ok to some extend because their code quality is not well(good code should always check if object exist,array length>0 etc before access them), what i concern is: i do not want the js app functions as if they crashed and not work anymore, even if the root cause which should cause above error disappear(for example, the array has been there now), the app will never survive to run again.
Is there some method to force js app to run even after 3rd party code fail(or my own code fail) but should SURVIVE to run for some other function area(which has no the crash causing there), or survive to work again if the cause for above exception disapper?
Please NOTE THAT, I DO NOT WANT TO TOUCH 3RD party code to let this work
Is there a generic mechanism in javascript to be switched on : just skip the un-caught error and continue to run as normal and NOT CRASH the app?
If you don't want to use try-catch
process.on('uncaughtException', err => {
console.error('There was an uncaught error', err)
process.exit(1) //mandatory (as per the Node.js docs)
})
If you don't exit the process, It can cause unexpected behaviour in your application which's why it recommended.
Further reading
As Nirus said, wrapping everything that could cause an error in a try...catch block:
try{
callYourLibHere();
}
Block should allow the code to ignore errors thrown, which will make the code continue to run after an error occurs. However, this will hide EVERY error inside this block. We can fix this by logging the errors into the console:
try {
callYourLibHere();
}
catch (e) {
console.log(e);
}
Please note that trying to solve the errors instead of ignoring them would be the better way to fix this.

Categories