ATM I'm working on a small project with node.js + express + mongodb. The logic is on web, but is loaded from my node.js server. Something like this in my index.html
<script src="./app.js"></script>
<script type="text/javascript">
var debug = false;
$(document).ready(function() {
app.start();
});
</script>
My test are functional -- meaning that I use a headless browser (Zombie) and I get good indications about the coverage with istanbul. I tried blanket unsuccessfully.
process.env['TEST'] = true;
var app = require('../server/JS_TPV.server.js');
var mongodb = require('mongodb');
var should = require("should");
var Browser = require("zombie");
var browser;
Then something like:
before(function(done) {
var populateDB = require('../install/JS_TPV.mongo_db_fill.js');
populateDB.install(function() {
browser = new Browser({debug:false, silent:false});
browser.visit("http://localhost:8080").then(done,done);
console.log("visited ending BEFORE");
});
});
But since index.html file is being accessed and all the js files on it are loaded, I think it should show it's coverage too.
Is any way to show this?
Or the only way to do this is by generating an html-kind of test where I check my web functions? (yeah, or with require.js and testing all the logic node-style).
Thanks!
You can :)
The key points are
the code executed by the browser has to be instrumented
someone must collect the coverage information
You can find an example of this working here: https://github.com/ericminio/yop-promises/blob/master/test/promises.with.browser.spec.js
run in order npm run cover and npm run report and navigate to coverage folder to find the report. Play around with not running Zombie test to see how that impacts code coverage.
This is one example with Zombie and Istanbul, so it really deals specifically with how those two tools can let you go through the 2 points above.
Related
I am linking to an external javascript file that will work locally on my machine in Chrome, but not on a remote server. It keeps breaking at line 27, the first textContent code. I have looked on this site for possible answers, but can't get it to work. I hoping someone on this site can spot a possible error.
Code file is attached.
Thanks.
-Shawn
window.addEventListener('load', function () {
var pathname = window.location.pathname;
if (pathname.indexOf('question_1') > -1) {
var Q1 = 'As a traffic engineer, Travis works for the State DOT to identify traffic safety issues and then to determine how to mitigate the issues via engineering improvements. What types of engineering improvements might be considered to improve motorcycle safety? Select all of the correct responses.';
var A1a = "Patching potholes";
var A1b = "Adding/changing road signage";
var A1c = "Placing billboards";
var A1d = "Conducting traffic stops";
var A1Correct = "As a traffic engineer, Travis can support the motorcycle safety mission by implementing engineering improvements that could include adding/changing road signage and/or patching potholes.";
var A1Incorrect = "As a traffic engineer, Travis can support the motorcycle safety mission by implementing engineering improvements that could include adding/changing road signage and/or patching potholes.";
document.querySelector('#text158 span').textContent = Q1;
document.querySelector("#text159 span").textContent = A1a;
document.querySelector("#text161 span").textContent = A1b;
document.querySelector("#text163 span").textContent = A1c;
document.querySelector("#text165 span").textContent = A1d;
document.querySelector("#text4750 span").textContent = A1Correct;
document.querySelector("#text4808 span").textContent = A1Incorrect;
}
}
You need to listen to DOMContentLoaded instead of load.
load fires when all files have downloaded (HTML/JS/CSS/Images)
DOMContentLoaded fires when the page has rendered
Solution
window.addEventListener('DOMContentLoaded', function() {
console.log('DOMContentLoaded');
// your code here (minus the console.log above)
});
I suspect the reason it worked locally is because you were including your JS somewhere BELOW the elements you're referencing, and now that it's remote, you're including the JS somewhere ABOVE the elements you're referencing.
Documentation
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
https://developer.mozilla.org/en-US/docs/Web/Events/load
I am looking for an npm/javascript based Automated Testing tool with which I can test my website providing scripted input values and then for example clicking submit button on page etc.
So far I have tested Dalekjs but it seems to have lots of problems especially with Firefox, plus some CSS selectors are also not working even in other Browsers.
Is there any other good Automation testing tool that is npm based but does not necessarily require Selenium?
Nightmare.js
There's a really awesome tool called Nightmare.js. First it was a hight-level Phantom wrapper, but since v2 it was rewritten on Atom. Nightmare is webkit-based.
Nightmare can be executed headlessly, but you'll probably need to configure your server to get that working.
Why Nightmare? Here's a code sample from the official site:
Nightmare.js
yield Nightmare()
.goto('http://yahoo.com')
.type('input[title="Search"]', 'github nightmare')
.click('.searchsubmit');
Comparing to:
Phantom.js
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open('http://yahoo.com', function (status) {
page.evaluate(function () {
var el =
document.querySelector('input[title="Search"]');
el.value = 'github nightmare';
}, function (result) {
page.evaluate(function () {
var el = document.querySelector('.searchsubmit');
var event = document.createEvent('MouseEvent');
event.initEvent('click', true, false);
el.dispatchEvent(event);
}, function (result) {
ph.exit();
});
});
});
});
});
So you'll have to write significantly less code.
BUT IT'S WEBKIT-ONLY
Selenium
In order to get something working in all browsers, take a look at Selenium. It supports really many browsers and platforms.
var webdriver = require('selenium-webdriver'),
By = require('selenium-webdriver').By,
until = require('selenium-webdriver').until;
var driver = new webdriver.Builder()
.forBrowser('firefox')
.build();
driver.get('http://www.google.com/ncr');
driver.findElement(By.name('q')).sendKeys('webdriver');
driver.findElement(By.name('btnG')).click();
driver.wait(until.titleIs('webdriver - Google Search'), 1000);
driver.quit();
Just a small advice Selenium tests are likely to be more "bulky" than nightmare tests and I've seen quite a lot "Promise hell" in Selenium tests on one of my previous jobs, so before you start, my advice to you would be to use of generators and co or some other control flow library.
try http://phantomjs.org/
It might be an excellent alternative to Dalekjs. Phantom.js is runnable without a UI, scriptable via JavaScript and is used for automating web page interaction. It's a WebKit with its own JavaScript API. It has fast and native support for most web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. You can use scripted input values
Here is a sample usage:
console.log('Loading a web page');
var page = require('webpage').create();
var url = 'http://en.wikipedia.org/';
page.open(url, function (status) {
console.log('Page loaded');
page.render('wikipedia.org.png');
phantom.exit();
});
I also had a similar requirement, I did below investigation which would be helpful:
NightmareJS is actually based on PhantomJS. It works very well even for a non-dev. In reality automated testing truly depends on many situations and the type of application tested. You need a super fast way to visually see if changes to the code is affecting the app visually and also to some degree its logic. For logic there are many other frameworks for that like selenium frameworks. No need for complex coding as you want to be able to view the application or test results quick, modify the variable or elements that neeeds to be tested and verified.
I have a PhantomJS (1.9) script "test.js" (Code taken from PhantomJS docs)-
var webPage = require('webpage');
var page = webPage.create();
page.open('http://m.bing.com', function(status) {
var title = page.evaluate(function() {
// >> I have a breakpoint here, but debugger doesnt stop!
return document.title;
});
console.log(title);
phantom.exit();
});
I am debugging this code with phantomjs --remote-debugger-port=9000 test.js and chrome.
I can reach to all code breakpoints except the code inside page.evaluate().
Is there a way to debug it?
This is and old question and the phantomJS engine has been legacy for quite some time now, but for all those who has to maintain legacy code just like me, here is a gif I've prepared that shows step by step process of how to debug phantomjs scripts and the page opened inside.
So what you need to do is put a breakpoint in the page script and copy the link of the current browser tab and increase the page number by one. this will attach the debuggger to the inside script and you will be able to debug your code.
you can check out the step by step gif(it was too big to uplo) =>https://gaziedutr-my.sharepoint.com/:i:/g/personal/ahmet_bekir_urun_gazi_edu_tr/EZUj5yMbgqJIpun7qBdfF5sB3QWWg1r5u3MwayiKsw4Lug?e=PXeS8t
I'm trying to make a simple firefox add-on, executing a simple stand-alone JS-script on every new page (say, just a simple alert after page loaded).
First, I've tried add-on sdk. It have been installed successfully, run tests, but was not able to execute even examples from any tutorial, so i tried to try XUL.
I downloaded 'xulschoolhello.xpi', unpacked it, modified content/browserOverlay.xul to this:
<?xml version="1.0"?>
<!DOCTYPE overlay SYSTEM
"chrome://xulschoolhello/locale/browserOverlay.dtd">
<overlay id="xulschoolhello-browser-overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript"
src="chrome://xulschoolhello/content/browserOverlay.js" />
</overlay>
and content/browserOverlay.js to this just to see if something happens:
window.alert(123)
but nothing happens after zip packing, installation and rebooting.
I'm quiet new to firefox extensions, so thanks for any help.
UPD.
I tried to make a very simple bootstrap.js:
var WindowListener = {
onOpenWindow: function(window) {
window.alert(123)
}
}
function startup(data, reason) {
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
wm.addListener(WindowListener);
}
function shutdown(data, reason) {}
function install(data, reason) {}
function uninstall(data, reason) {}
But it doestn alert. What am i doing wrong here?
This is a fully working bootstap addon that runs javascript everytime a url matching hostPatern of bing.com is loaded. Download the xpi from this gist here and install it to see it working:
https://gist.github.com/Noitidart/9287185
If you want to use this for yourself, then just edit the addDiv and removeDiv functions on the js you want to run. And to control which site edit hostPattern global var and decide if you want to listen to frames by setting global var of ignoreFrames.
To accomplish this with addon-sdk you do it like this:
var pageMod = require("page-mod");
const data = require("self").data;
exports.main = function() {
pageMod.PageMod({
include: ["https://www.bing.com/*","http://www.google.com/*"],
contentScriptWhen: 'ready',
/*contentScriptFile: [data.url("jquery.js"),data.url("script.js")],*/
onAttach: function(worker) {
console.log('loaded a page of interest');
}
});
I'm not too familiar with addon-sdk like i dont know how to set up the environment, but i heard once you get it setup its pretty simple. As you can see by comparing the amount of code. But in the bootstrap version you have fine control over everything thats why I prefer bootstrap, and most of the codes are cookie-cutter copy and paste.
What's the simplest way to launch Firefox, load a 3rd party website (which I'm authorised to "automate"), and run some "privileged" APIs against that site? (e.g: nsIProgressListener, nsIWindowMediator, etc).
I've tried a two approaches:
Create a tabbed browser using XULrunner, "plumbing" all the appropriate APIs required for the 3rd party site to open new windows, follow 302 redirects, etc. Doing it this way, it's an aweful lot of code, and requires (afaict) that the user installs the app, or runs Firefox with -app. It's also extremely fragile. :-/
Launch Firefox passing URL of the 3rd party site, with MozRepl already listening. Then shortly after startup, telnet from the "launch" script to MozRepl, use mozIJSSubScriptLoader::loadSubScript to load my code, then execute my code from MozRepl in the context of the 3rd party site -- this is the way I'm currently doing it.
With the first approach, I'm getting lots of security issues (obviously) to work around, and it seems like I'm writing 10x more browser "plumbing" code then automation code.
With the second approach, I'm seeing lots of "timing issues", i.e:
the 3rd party site is somehow prevented from loading by MozRepl (or the execution of the privileged code I supply)???, or
the 3rd party site loads, but code executed by MozRepl doesn't see it load, or
the 3rd party site loads, and MozRepl isn't ready to take requests (despite other JavaScript running in the page, and port 4242 being bound by the Firefox process),
etc.
I thought about maybe doing something like this:
Modify the MozRepl source in some way to load privileged JavaScript from a predictable place in the filesystem at start-up (or interact with Firefox command-line arguments) and execute it in the context of the 3rd party website.
... or even write another similar add-on which is more dedicated to the task.
Any simpler ideas?
Update:
After a lot of trial-and-error, answered my own question (below).
I found the easiest way was to write a purpose-built Firefox extension!
Step 1. I didn't want to do a bunch of unnecessary XUL/addon related stuff that wasn't necessary; A "Bootstrapped" (or re-startless) extension needs only an install.rdf file to identify the addon, and a bootstrap.js file to implement the bootstrap interface.
Bootstrapped Extension: https://developer.mozilla.org/en-US/docs/Extensions/Bootstrapped_extensions
Good example: http://blog.fpmurphy.com/2011/02/firefox-4-restartless-add-ons.html
The bootstrap interface can be implemented very simply:
const path = '/PATH/TO/EXTERNAL/CODE.js';
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
var loaderSvc = Cc["#mozilla.org/moz/jssubscript-loader;1"];
.getService(Ci.mozIJSSubScriptLoader);
function install() {}
function uninstall() {}
function shutdown(data, reason) {}
function startup(data, reason) { loaderSvc.loadSubScript("file://"+path); }
You compile the extension by putting install.rdf and bootstrap.js into the top-level of a new zip file, and rename the zip file extension to .xpi.
Step 2. To have a repeatable environment for production & testing, I found the easiest way was to launch Firefox with a profile dedicated to the automation task:
Launch the Firefox profile manager: firefox -ProfileManager
Create a new profile, specifying the location for easy re-use (I called mine testing-profile) and then exit the profile manager.
Remove the new profile from profiles.ini in your user's mozilla config (so that it won't interfere with normal browsing).
Launch Firefox with that profile: firefox -profile /path/to/testing-profile
Install the extension from the file-system (rather than addons.mozilla.org).
Do anything else needed to prepare the profile. (e.g: I needed to add 3rd party certificates and allow pop-up windows for the relevant domain.)
Leave a single about:blank tab open, then exit Firefox.
Snapshot the profile: tar cvf testing-profile-snapshot.tar /path/to/testing-profile
From that point onward, every time I run the automation, I unpack testing-profile-snapshot.tar over the existing testing-profile folder and run firefox -profile /path/to/testing-profile about:blank to use the "pristine" profile.
Step 3. So now when I launch Firefox with the testing-profile it will "include" the external code at /PATH/TO/EXTERNAL/CODE.js on each start-up.
NOTE: I found that I had to move the /PATH/TO/EXTERNAL/ folder elsewhere during step 2 above, as the external JavaScript code would be cached (!!! - undesirable during development) inside the profile (i.e: changes to the external code wouldn't be seen on next launch).
The external code is privileged and can use any of the Mozilla platform APIs. There is however an issue of timing. The moment-in-time at which the external code is included (and hence executed) is one at which no Chrome window objects (and so no DOMWindow objects) yet exist.
So then we need to wait around until there's a useful DOMWindow object:
// useful services.
Cu.import("resource://gre/modules/Services.jsm");
var loader = Cc["#mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader);
var wmSvc = Cc["#mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
var logSvc = Cc["#mozilla.org/consoleservice;1"]
.getService(Ci.nsIConsoleService);
// "user" code entry point.
function user_code() {
// your code here!
// window, gBrowser, etc work as per MozRepl!
}
// get the gBrowser, first (about:blank) domWindow,
// and set up common globals.
var done_startup = 0;
var windowListener;
function do_startup(win) {
if (done_startup) return;
done_startup = 1;
wm.removeListener(windowListener);
var browserEnum = wm.getEnumerator("navigator:browser");
var browserWin = browserEnum.getNext();
var tabbrowser = browserWin.gBrowser;
var currentBrowser = tabbrowser.getBrowserAtIndex(0);
var domWindow = currentBrowser.contentWindow;
window = domWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
gBrowser = window.gBrowser;
setTimeout = window.setTimeout;
setInterval = window.setInterval;
alert = function(message) {
Services.prompt.alert(null, "alert", message);
};
console = {
log: function(message) {
logSvc.logStringMessage(message);
}
};
// the first domWindow will finish loading a little later than gBrowser...
gBrowser.addEventListener('load', function() {
gBrowser.removeEventListener('load', arguments.callee, true);
user_code();
}, true);
}
// window listener implementation
windowListener = {
onWindowTitleChange: function(aWindow, aTitle) {},
onCloseWindow: function(aWindow) {},
onOpenWindow: function(aWindow) {
var win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
win.addEventListener("load", function(aEvent) {
win.removeEventListener("load", arguments.callee, false);
if (aEvent.originalTarget.nodeName != "#document") return;
do_startup();
}
};
// CODE ENTRY POINT!
wm.addListener(windowListener);
Step 4. All of that code executes in the "global" scope. If you later need to load other JavaScript files (e.g: jQuery), call loadSubscript explicitly within the null (global!) scope
function some_user_code() {
loader.loadSubScript.call(null,"file:///PATH/TO/SOME/CODE.js");
loader.loadSubScript.call(null,"http://HOST/PATH/TO/jquery.js");
$ = jQuery = window.$;
}
Now we can use jQuery on any DOMWindow by passing <DOMWindow>.document as the second parameter to the selector call!