Strange variable undefined error in console.log - javascript

Can someone explain why the console acts this way?
I posted this question once, but I could not quite formulate it correctly so I closed it again. The initial question did not mention that the problem could be console related, I just questioned the strange behavior of the variables. I basically only posted the following screenshot:
Note here that I log $s.page on line 20 and $s.page.navi is there, and on line 21 when I log again it's gone.
Reopening the question
There was nobody who could give an answer, although #zerkms suggested it could have something to do with the console itself. After I closed the question he contacted me via this post: Have require.js load my files only when I actually need them to maybe reopen the question.
The Problem
Enough intro, back to the issue. So where did the variable go. From the other question I posted you can see I use require.js to load my files. I am kinda new to this all so my problem was related to it.
In the code of $s.page I do the following (simplified):
require(['nav'], $.proxy(function(Nav){
this.navi = new Nav.Views.Main();
}, this));
nav is a module that require.js has to load. I the script would block until the file is there, and looking at the console it confirmed that.
Let me log in more detail:
console.log('x');
require(['nav'], $.proxy(function(Nav){
console.log('y');
this.navi = new Nav.Views.Main();
}, this));
I left the other logs in place aswel, and here is the output:
Notice that x is logged first. When I then log $s.page it shows me what $s.page will look like in the future, i guess. Really odd.
When I then log $s.page.navi on the next line it is not there, which is correct.
Then at the very end, without even being called anymore, y joins the party.

See on line 22 of router.js I call $s.page.navi.start(), that was the whole point of this problem. It could not be fired. I solved it with the following code:
require(['nav'], function(Nav){
$s.page.navi.start();
});
It will just wait for it's dependencies.
Conclusion
When working with JavaScript, and libraries such as backbone.js and require.js you should really keep track of what you are doing and keep in mind that the script does not easily block.
Just logging at certain points in the application will not always help you solve your problem, you have to really log from the root of your application to the tip of the leaf to see what is actually happening. And the best approach is always the build in debugger.

Related

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.

Is there a way to break on warnings in Google Chrome?

I want to see the warnings in order to do a better debugging of my application which is made in Asp.Net, so it has a lot of code generated in javascript. The problem is that pages reload fast and I can't take a look at the warning messages. I want to know if there is a way to break on warnings in Google Chrome, as in this question is described how to break on errors. Is there a way to do this, or what alternatives do I have?
As #Nitsew has already said, preserving the log is a great solution. But just for fun, and because I thought your question was interesting, I decided to work out a solution to do what you asked; cause a debug to occur when warn is used:
function testBreak() {
console.warn('This is a warning', 1, 2);
return 1;
}
var oldWarningFunction = console.warn;
console.warn = function () {
debugger;
oldWarningFunction.apply(console, arguments);
};
console.log(testBreak());
Essentially, I have monkey-patched the original console.warn to output a debugger statement. When this causes the debug to occur, you will probably need to view the stack trace to see where you were in the code:
Once you click back one on that stack trace, you can see the function that made the call.
This all seems rather silly since you could just write your own debugger statement right in your code where you want them. And one other thing, to whoever may read this and tries it: Do not leave this in your production code
If you are just trying to look at the console messages, turning on "Preserve log" might be an easier solution.

How to catch typos errors in VIM for EmberJS (Javascript)

I am starting to learn EmberJS/JS/VIM . I was going through the official ToDoMVC guide for EmberJS, and I ran into typos errors that was really really hard to detect with the "eyes" and the browser really didn't help in this case at all. So, can you please suggest me what tools or techniques that can be used to detect these types of typos errors?
For example:
### todo_controller should've been todos_controller
<script src="js/todo_controller.js"></script>
### catching the end of { } closed scoping
### typo within a model js "property"
inflection: function() {
var remaining = this.get('remaining');
return remaining === 1 ? 'todo' : 'todos';
}.proprety('remaining')
EDIT;
Yes, I did search before posting here. The first was this website, and the comments here basically suggest DreamWeaver Frustration with Typos.
I searched SO itself (through google), and there was Is there a way to catch typos. I did find out there is something called LINT, but it dealt with coffeescript.
I did find out ember.vim as you pointed out before, but as you see the README in the github profile, i believe it strictly wants you to follow the layout as prescribed. It may be a good thing in future, but right now, I wanted to just stick with what the official ToDoMVC way. I am just beginning to get a hang of hjkl, so I do not think I can makes changes to it to fit my way. Also, second point, is the layout format it supports is Ember-AppKit which has been deprecated. SO I am having doubts if I should follow the layout pattern itself.
And all of them didn't particularly address what I am asking. In the todo_controller typo above, the browser didn't throw any sort of errors. I am using FF/Firebug, and on the Console, it only showed the message about Ember loading, and no errors at all. It took me a while to see that typo. The second one did throw errors, but typos are a hard thing to discover in VIM. The third one, took a bit of time, and there were others. These don't throw errors at all. I am used to PHP, and while there is no direct showing of errors as in Android, I am finding Javascript typo hunting to be very hard.
it took me like 3 looks before I saw your typo.
Set your browser to pause on exceptions (sometimes pause on Caught Exceptions). It's been one of the quickest ways I've found to track down a weird bug. In this case I'm sure you were getting Uncaught TypeError: undefined is not a function....
Don't take this the wrong way, but did you try to search before asking? There has been, for quite a while now, a plugin for Vim that has syntax highlighting improvements.
https://github.com/dsawardekar/ember.vim
Beyond that plugin, you could try writing your own solution. I haven't tried, but I doubt there is anything out there that will pick up spelling errors for Ember...
I use JSLint for SublimeText 3, which lints as you code so you get a live update of any potential bugs. Kinda nice. Here's something similar for Vim: https://github.com/hallettj/jslint.vim
As #kingpin2k suggests, you should really learn how to use your browser tools. The big three are just jam-packed full with development and debug tools. 9 times out of 10 it gives you the line and column of the error, and you can set breakpoints within the code to watch it execute in-context. And, that is really just the tip of the iceberg in terms of how detailed you can get with debugging in-browser.

JS fails unless the console is open

I'm truly stumped by this problem.
I've got some JavaScript to control a product configurator.
A simple bit of code to select some defaults
works fine in Chrome
works fine in IE
doesn't work in Firefox (newest versions of everything)
However, if I do anything to observe the code in FF it works fine.
If I have it alert anything relevant, it works.
If I log anything relevant, it works, but only if the console is actually open so I can see the log. If the console isn't open, doesn't work.
for(type in radio_groups) {
if_checked = !!$(":radio[name="+type+"]:checked").length;
console.log($('.'+type).not('[class*="unavailable"]'));
//This loop doesnt do anything without this log above
alert($('.'+type).not('[class*="unavailable"]'));
// Or this alert.
var t = $('.'+type).not('[class*="unavailable"]');
// Line above doesn't make stuff work.
if(!if_checked)
$('.'+type).not('[class*="unavailable"]').first().click();
}
if_checked is false for every type, I can verify that when it runs.
However, nothing happens.
No buttons are clicked.
This is plain single threaded JS in a browser.
There's no interval/timeout functions on the page.
I can do time arbitrary time consuming tasks before the last line (my best idea was that it was a concurrency issue somehow, I don't see how else logging could affect anything) and it doesn't have any effect.
I can run the same selector and put it in a string, or do anything you can think of to it besides logging or alerting and it wont work; no buttons get clicked. Only actively observing whats happening makes the code work. The entire deal is rather involved and I cant provide the entire thing.
Any ideas on how:
logging can possibly affect the outcome of a simple click event?
why this is Firefox specific? Or other ways I might try to see whats going wrong without the console or alerts?
Edit: Oh, and I've had two other people replicate the issue in their browsers (again, Firefox only), so its not some wonky extension issue unless we all share it.
Thanks.
This line is not valid:
var t = "$('.'+type).not('[class*="unavailable"]')";
It should probably be:
var t = "$('.'+type).not('[class*=\"unavailable\"]')";
or:
var t = $('.'+type).not('[class*="unavailable"]');
Here's a bit of speculation:
if_checked = !!$(":radio[name="+type+"]:checked").length;
It looks like the quotes aren't paired correctly. Did you mean this?
if_checked = !!$(":radio[name='"+type+"']:checked").length;
(See the single quotes that wrap the value of type?)
I've come across this before. If I'm leaving any logging in place in production code I'd wrap it in a try > catch statement.
try {
console.log("my log message")
} catch (err) { };
I know it's considered bad practice to have an empty 'catch' but hey, it's also bad practice to leave the logging in on priduction code.
It seems in FF (also in older IE) if the console is not open then it doesn't exist so the error being caught is probably something like 'console is undefined'

printing out error messages in the javascript version of processing

To make a long story short I have to use processing in a class and I'm completely blind. The ide is completely inaccessible so I use the JavaScript version of processing to create a page and have a sited person describe the output to me. Unfortunately if the code has errors the page appears blank and there is no explanation of what’s wrong. Given the following code is there a way for the JavaScript version of processing to tell me that I have a syntax error since I forgot );
void setup()
{
size(500, 500);
}
void draw()
{
line(250, 200, 250, 40
}
Well for debuging (when the code compiles) you can use the println() command.
I've been using processing for 2 months now and i have the same problem and haven't been able to find a solution for it.
Here in SO for what I've seen almost no one uses Processing or knows how to use it. You can try the processing forums, you'll normally get an answer in a day or two. You can find that here http://processing.org/discourse/
Sorry for not being able to help. The other only solution I see is if you use their PDE (Processsing develop environment) and compile it there.
Edit: From previous experience asking processing questions you won't even have much ppl looking into your question :(
A js editor with syntax highlighting (such as Aptana) will show you errors such as you have there.
I don't know whether you'd find that any more useful than the Processing ide itself, though.
When you open the page in a browser, make sure you have the developer tools open. They come with every major browser (look in the tools menu), and include a JavaScript console. This will include any errors you get from the Processing.js parser.
I'm not sure if there are more accessible versions of the developer tools, but that would be a good place to start.
in processing.js, use createCanvas();
instead of size,
thus:
createCanvas(500, 500);

Categories