Sorry I don't know if this is a stupid question or not but I cannot find the answer.
I have a pure function in javascript which check if the argument is a correct URL
isValidUrl(url) {
const protocol = new URL(url).protocol;
...
}
The code runs fine in browser. But I would like to write a test using mocha for it. And mocha complains "ReferenceError: URL is not defined". So does that mean server side JS does not have URL class? Do I need to use something like headless browser to test it?
Thanks a lot.
Node and friends, where your tests are likely running, implement the ECMAScript (JS) spec. The URL class is from this WhatWG spec. The JS spec does not have any reference to a URL class, which explains your immediate problem.
Node also implements its own CommonJS-based modules, one of which is a URL module. It doesn't appear to have the same interface, however.
Using Mocha with Karma to run tests in a headless browser, like PhantomJS, is probably a better solution. You'll get an accurate, if slightly out of date, version of chromium to test within. You can also set Karma up to use other browsers, if they are available on the test machine.
Related
So this may be naive, but can I run node only style apps in the browser? I've see tuts for frontend stuff. I've seen tuts for backend stuff. I want to run https://github.com/lapwinglabs/x-ray in a browser and do something quick and dirty like (this code may not be perfect)
$(document).ready(function() {
var phantom = require('x-ray-phantom');
var Xray = require('x-ray');
var x = Xray()
.driver(phantom());
x('http://google.com', 'body')(function(err, str) {
$( "body" ).replaceWith( "str" );
});
});
To do a whole site pass though without an iframe. The purpose is so I can re-write CSS on internal company assets in sort of a global fashion. I'll be able to just pass a url and the page will be displayed. If I have custom css for it, then that will be active. I still gotta work out auth, but im not worried about it at this exact moment.
I've used x-ray with express in the past and it worked like a charm. In this context though I've taken a liking to Laravel and would like to stand up my apps in that.
The latest Laravel has "mix", a web pack front end. It works great for frontend assets. If I try to webpack x-ray though, I run into a flurry of issues like:
Module not found: Error: Can't resolve yadayadayada
So you can set an export like this:
module.exports.node = {
fs: 'empty',
net: 'empty',
tls: 'empty'
};
While that fixes module errors, I feel like I need those things. and in the browser I get:
Uncaught Error: Cannot find module "child_process"
I have a feeling things like this are not supposed to work, but I'm hoping I'm mistaken.
The simple answer is: you can't use Node built-in modules like fs or net, and therefore modules that use them, in the browser.
You can empty them out as you did with the node option, but the modules that depend on them use them for a reason and you would break them, unless you know exactly that the part, that uses the built-in modules, will not end up in your application, or at least you're not using it.
In your case, first it complained about fs, which clearly doesn't make sense in the browser, because you don't have access to the file system. And then it complains about child_process, so somewhere in the module it spawns processes, but you can't do that in the browser either, and emptying that out will very likely break the module's functionality, so you'd need to look for another module, that can be used in the browser.
I`m using phpstorm with protactor for angular and for some reason the IDE doesnt recognize some
functions. but the functions is working fine when i`m running the test.
for example:
element(by.buttonText('toggle')).click();
expect(element(by.css('.net-fade')).getText()).
toEqual('something');
})
The IDE tell me that the method by.css is "unresolved function or method".
Someone know how to fix it?
I'm not familiar with PHPStorm, so this won't be a full-answer:
But I'd say the basic problem is that Protractor binary auto-inserts protractor.js and other dependencies into the environment for you. This is what gives you by (along with other helper variables browser, element, etc).
You may want to insert protractor.js yourself, you can find it in
node_modules/protractor/lib/protractor.js
(And again, I am unsure of how PHPStorm includes files, but you might want to only manually add protractor.js if it is not running in test mode. And to this end, you could set flag in protractors onPrepare() function to check against).
Trying to add tests support into my project. Attached JsTestDriver with coverage plugin.
Dummy tests are working correctly, but when I load up all my source files I'm getting application crashed with the following:
[java] **line 109:12 no viable alternative at input 'formFound'**
[java] Exception in thread "main" com.google.jstestdriver.coverage.CodeInstrumentor$InstrumentationException: error instrumenting /path/discover.js
[java] at com.google.jstestdriver.coverage.CodeInstrumentor.instrument(CodeInstrumentor.java:74)
[java] at com.google.jstestdriver.coverage.CoverageInstrumentingProcessor.process(CoverageInstrumentingProcessor.java:62)
This line of code looks like:
let formFound = tryToFindLoginForm();
I changed that definition into
var formFound = tryToFindLoginForm();
After that JSTD will pass over that string but will die on next let statement. Is there any way to workaround this, to tell JSTD the version of javascript used in code or something?
It'll be a very big issue to rewrite entire code into version without lets.
Thanks for help in advance.
I'm trying to create a node.js app and
alert('Sample Alert');
is causing my program to crash. Node says
ReferenceError: alert is not defined
and then quits. I can use the alert function when running javascript on a regular html page, so I'm at a loss to understand why this is... Is this a separate module that I have to use with node.js?
The alert() function is a property of browser window objects. It is not really part of JavaScript; it's just a facility available to JavaScript code in that environment.
Try console.log("Hello World");
alert() function is only available when you execute JavaScript in the special context of browser windows. It is available through the window object.
Node.js is not intended for writing desktop applications (directly). It is mainly intended for writing server-side JavaScript applications. You can use following frameworks/packages (and many more) if you want to develop true desktop applications.
Electron
NW.js (previously, node-webkit)
NW.js is an app runtime based on Chromium and node.js. You can write native apps in HTML and JavaScript with NW.js. It also lets you call Node.js modules directly from the DOM and enables a new way of writing native applications with all Web technologies.
AppJS
Available as an standalone distributable and an npm package
Meanwhile, you can use console.log() to output a message in Node.js.
console.log('hello');
While these answers are "correct", as there is no alert function available outside of the browser, there's no reason you can't create one and then use it:
node -e "function alert(x){
x === 'undefined' ? console.log('undefined') : console.log(x); return;
};
alert('x'); alert();"
results:
x
undefined
Then you might not need to change your existing code or example or whatever.
You'll also need code to wait for a key. Here's a start:
process.stdin.on('char', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
process.stdout.write('data: ' + chunk + 'got?\n');
}
});
alert function is for browsers. means front end..in nodejs for printing in cmd or bash you should use this one..
console.log("Sample alert");
you can print any variable or constant here... for printing variables just remove quotes
The alert() property is only allowed by browsers, not JavaScript.
Since things like DOM and alerts are made for your browser to execute, you cannot use them in your nodejs environment.
Use
console.log('Sample Alert');
or if you want to use DOM or alerts, follow-->
What you can do is, first make a separate .js file for your HTML file and then link those two...
Note: Make sure the path is right (For .ejs users, make sure to give a path relative to your public folder) and now you can use your alerts.
Hope this helps.....
I don't see where it is documented but I have been using global.alert() in my react-native code. I am using it for debugging purposes because I am running an Appium test so I don't have access to the console.log() output.
We are refactoring a legacy web app and as a result are "killing" quite a lot of JavaScript code but we're afraid of deleting what we think is dead code due to not being sure. Is there any tool / technique for positively identifying dead code in JavaScript?
Without looking for anything too complex:
JSLint (not really a static analyzer, but if you give it your concatenated development code, you'll see what methods are never called, at least in obvious scoping contexts)
Google Closure Compiler
Google Closure Linter
You can use deadfile library:
https://m-izadmehr.github.io/deadfile/
It can simply find unused files, in any JS project.
Without any config, it supports ES6, JSX, and Vue files:
There's grep. Use it to find function calls. Suppose you have a method called dostuff(). Use grep -r "dostuff()" * --color on your project's root directory. Unless you find anything other than the definition, you can safely erase it.
ack is also a notable alternative to grep.
WebStorm IDE from JetBrains can highlight deadcode and unused variables in your project.
You could use code optimizers as Google Closure Compiler, however it's often used for minimizing code.
function hello(name) {
alert('Hello, ' + name);
}
function test(){
alert('hi');
}
hello('New user');
Will result in
alert("Hello, New user");
For example.
Another thing you could do is to use Chrome's Developer Tools (or Firebug) to see all function calls. Under Profiles you can see which functions are being called over time and which are not.
Chrome has come up with new feature which lets developer see the code coverage, ie., which lines of codes were executed.
This certainly is not a one stop solution, but can extend a helping hand to developers to get code insights.
Check this link for details
Rolled as apart of Chrome 59 release
If you want to automate this I'd take a look at https://github.com/joelgriffith/navalia, which exposes an automated API to do just that:
const { Chrome } = require('navalia');
const chrome = new Chrome();
chrome.goto('http://joelgriffith.net/', { coverage: true })
.then(() => chrome.coverage('http://joelgriffith.net/main.bundle.js'))
.then((stats) => console.log(stats)) // Prints { total: 45913, unused: 5572,
percentUnused: 0.12135996340905626 }
.then(() => chrome.done());
More here: https://joelgriffith.github.io/navalia/Chrome/coverage/
I hate this problem, and that there are no good tools for solving it, despite the parse-heavy javascript ecosystem. As mentioned in another answer, deadfile is pretty neat, but I couldn't make it work for my codebase, which uses absolute imports from a src directory. The following bash was good enough to get an idea of whether any files weren't imported anywhere (I found some!), which was easily hand-verifiable.
for f in $(find src -name '*.js' | grep -E 'src/(app|modules|components).*\.js$' | grep -v '.test.js'); do
f=${f/src\//};
f=${f/\/index.js/};
f=${f/.js/};
echo "$f imported in"$(grep -rl "$f" src | wc -l)" files"
done
I didn't care about tests/resources, hence the app|modules|components bit. The string replacements could be cleaned up significantly too, but hopefully this will be useful to someone.