How to run all test scripts on a single browser instance - javascript

I am using Testcafe (free version) with Java Script. I want to run all my test cases (resides in multiple test scripts in __test__ directory) in a single browser instance (That way 1 time log in) per browser type.
For example, 1 instance for chrome and 1 instance for safari but all tests will run before closing the browser.
If a test fails, I want the screenshot is taken and count number of the test failures. But do want to continue.
I'm doing all on Node 12 Docker image, so it is best if I don't need to install anything else.
How do I do this with Testcafe?
const createTestCafe = require('testcafe')
let testcafe = null
let runner = null
createTestCafe('localhost', 1337, 1338)
.then(tc => {
testcafe = tc
const runner = testcafe.createRunner()
return runner
.src([ '__test__/*.js' ])
.browsers([ 'chrome:headless --no-sandbox --disable-gpu', 'safari' ])
.screenshots('./reports/screenshots/', true)
.run({
selectorTimeout: 10000,
assertionTimeout: 10000,
})
})
runner
.screenshots({
path: 'reports/screenshots/',
takeOnFails: true,
})
.then(failedCount => {
console.log('Tests failed: ' + failedCount)
testcafe.close()
})
.catch(error => {
console.log("An ERROR detected:" + error)
})
This is how you install chrome on Dockerfile. Can someone tell me how to install Firefox on Dockerfile?
RUN sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' && \
http_proxy=${http_proxy} https_proxy=${https_proxy} apt-get update && \
http_proxy=${http_proxy} https_proxy=${https_proxy} apt-get install -y --allow-unauthenticated google-chrome-stable && \
apt clean && rm -rf /var/lib/apt/lists/*

It's impossible to meet all requirements at once.
1) For example, 1 instance for chrome and 1 instance for safari but all tests will run before closing the browser.
You cannot install the Chrome and Safari web browsers on docker image. It's possible to install only Chromium and Firefox on it. See the Using TestCafe docker help topic for more information.
2) If a test fail, I want the screen shot taken and count number of test failed. But do want to continue.
TestCafe's Live mode works in the same way, but it's not available on docker.

This case you need to use Session Handling
During test execution, the Selenium WebDriver has to interact with the browser all the time to execute given commands. At the time of execution, it is also possible that, before current execution completes, someone else starts execution of another script, in the same machine and in the same type of browser.
more details

Related

Unexpected stdout of "'Saved file tree to doc-filelist.js\n' + 'Copied JS to doc-script.js\n' + 'Compiled CSS to doc-style.css\n'

I am working on a Docker Swarm data visualization tool with a team.
It works as follows:
Our backend is set up in a way that terminal commands can be executed from our code, where these terminal commands have been promisified and the result of this command should be a string of nodeIDs corresponding to the active nodes in my Docker Swarm. This data is then passed to another helper function, however, I am unable to move past the previously explained step due to an unexpected output from my promisified terminal command.
const getNodeIDs = () => {
console.log('in nodeID helper function');
return execProm("docker node ls --format '{{json .ID}}'").then(
(rawNodeIDs) => {
console.log('rawNodeIds: ', rawNodeIDs);
const parsedNodeIDs = parseRawData(rawNodeIDs);
console.log('parsedNodeIDs: ', parsedNodeIDs);
return parsedNodeIDs;
}
);
};
My code fails on line 6 due to the fact that the data being passed to my parseRawData function is not what it is expected. The console log on line 5 above returns as follows:
{
stdout: 'Saved file tree to doc-filelist.js\n' +
'Copied JS to doc-script.js\n' +
'Compiled CSS to doc-style.css\n',
stderr: ''
}
In addition to this being the wrong output, every time I invoke this command, a new file is created in my codebase labeled "docs" with the following three files inside: doc-filelist.js, doc-script.js, doc-style.css. I am working in a team of 4 other engineers, and I seem to be the only person experiencing this behavior. When I attempt to run the terminal command (featured on line 3 in the first block of code) directly in the terminal itself, I receive the expected output of
"odwch32vsynhxbc0ia2nwicag"
which is the nodeID of the single node currently in my Docker Swarm and what I should be receiving when invoking the terminal command from the code.
I've only been able to find one other stack overflow article dealing with the same issue in which that person was told to try running the terminal command
npm uninstall -g docker
which I have done, and this did not fix my issues. I've also looked into making edits to the Docker daemon itself, but am unsure that this is the real root of the issue. Since I am the only person on my team that seems to be encountering this bug, I have reason to believe that this error has something to do with my dev environment. My containers are running on Docker v4.15.0 and I am working on macOS on an M1 chip computer.
Thanks!

Error running forever.js on Windows - "'C:\Program' is not recognized as an internal or external command, operable program or batch file"

I am trying to run forever.js via the Windows command prompt and I get the following output:
>npm i -g forever
/my-project>forever start index.js
Log output:
'C:\Program' is not recognized as an internal or external command, operable program or batch file
I think it's something to do with the PATH that forever is using for the node binary, but I don't know how to fix it...
EDIT: Forever is using the following command (which is surrounded by quotes " "):
"C:\Program Files\nodejs\node.exe"
If you type dir /x in the root of c:, you can see the short name of the directory.
So, try the following instead:
C:\PROGRA~1\nodejs\node.exe
installing forever version 1.0.0 solved the problem for me
i have the same problem with forever 2.0.0.
I use a workaround in "forever.js": (I start my app by "node forever.js" )
const configChild = {
//
// Basic configuration options
//
silent: true, // Silences the output from stdout and stderr in the parent process
'killTree': true, // Kills the entire child process tree on `exit`
....
}
// =======================================================
// **Workaround for Windows**
// =======================================================
if (process.platform === 'win32' && process.execPath == "C:\\Program Files\\nodejs\\node.exe") {
configChild.command = '"C:\\PROGRA~1\\nodejs\\node.exe"';
}
const child = new (forever.Monitor)('app.js', configChild);
....
child.start();

Create React App not reusing existing tab

I have been developing a web app (for a few months) that is built on top of CRA. Everything has been working as intended until this morning when I realized that the npm (or yarn) start script is no longer reusing the existing tab I have open in Chrome. It instead opens a new tab at localhost:3000 even if there are existing tabs at localhost:3000. I have been investigating this for a few hours but am yet to find a solution. I added a log statement in the CRA script (within my node modules) that handles the reusing of existing tabs upon startup of the app.
function startBrowserProcess(browser, url) {
// If we're on OS X, the user hasn't specifically
// requested a different browser, we can try opening
// Chrome with AppleScript. This lets us reuse an
// existing tab when possible instead of creating a new one.
const shouldTryOpenChromeWithAppleScript =
process.platform === 'darwin' &&
(typeof browser !== 'string' || browser === OSX_CHROME);
if (shouldTryOpenChromeWithAppleScript) {
try {
// Try our best to reuse existing tab
// on OS X Google Chrome with AppleScript
execSync('ps cax | grep "Google Chrome"');
execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
cwd: __dirname,
stdio: 'ignore',
});
return true;
} catch (err) {
console.log(err);
// Ignore errors.
}
}
This is the output of the log statement:
{ Error: Command failed: osascript openChrome.applescript "http://localhost:3000/"
at checkExecSyncError (child_process.js:621:11)
at execSync (child_process.js:658:13)
at startBrowserProcess (/Users/***/Desktop/WorkSpace/React/***/node_modules/react-dev-utils/openBrowser.js:78:7)
at openBrowser (/Users/***/Desktop/WorkSpace/React/***/node_modules/react-dev-utils/openBrowser.js:122:14)
at Server.devServer.listen.err (/Users/***/Desktop/WorkSpace/React/***/node_modules/react-scripts/scripts/start.js:100:7)
at Server.returnValue.listeningApp.listen (/Users/***/Desktop/WorkSpace/React/***/node_modules/webpack-dev-server/lib/Server.js:604:10)
at Object.onceWrapper (events.js:273:13)
at Server.emit (events.js:182:13)
at emitListeningNT (net.js:1328:10)
at process.internalTickCallback (internal/process/next_tick.js:72:19)
status: 1,
signal: null,
output: [ null, null, null ],
pid: 2691,
stdout: null,
stderr: null }
It seems to have an issue running the Applescript command that handles this but I am unsure why. One of the other developers that is working on the same app locally is not having this issue. One change I made recently was upgrading to the new macOS Mojave. But the other developer just upgraded as well and is not having this issue.
Does anyone know what could be wrong?
To avoid opening a new tab,
you'll need to create an .env file in the root of your project and add this line,
BROWSER=none.
As shown here
Turns out after I upgraded Mojave I denied interface access to Google Chrome from my terminal. So it was unable to run the "reuse" tab script.

Mojo::UserAgent and JavaScript

I wondering if something like the below could be possible to do with Mojo::UserAgent :
let's say i have the below code :
my $ua = Mojo::UserAgent->new;
my $res = $ua->get('mojolicious.org/perldoc')->result;
is it possible to intercept Mojo::UserAgent request and send it to other web client which know javascript where its result sent back as as Mojo::Transaction::HTTP ($res above ),where the user can continue use Mojo::UserAgent interface results .
i.e i want the following :
Mojo::UserAgent-> HTTP request -> intercept the HTTP Request -> Send the HTTP Request to web client support javascript like WWW::Chrome::Mechanize or FireFox::Marionette -> the JavaScript Web Client do the request -> the returned result intercepted and changed to Mojo::Transaction::HTTP
or
Mojo::UserAgent -> non blocking HTTP request ->non blocking HTTP response -> send to embedded web browser like webkit -> get the result as Mojo::Transaction::HTTP
Any ideas /examples how to let Mojo::UserAgent work with javascript?
It's almost always possible but the actual question is the amount of work you'd do to accomplish it. Part of this particular answer is how you'd want to intercept requests. That's the easy part because you can wrap the start method (as Mojo::UserAgent::Role::Queued does).
After you intercept the request, do whatever you like. Get the raw response and have Mojo parse it and build that part of the transaction. After that you re-enter the normal progression.
For awhile people would recommend the headless browser phantomjs but it looks like that project has stalled. There's Joel Berger's Mojo::Phantom but that's not quite what you want.
Lastly, remember that almost everyone would like this to exist but it doesn't. That's important information there. ;)
If you still want to work on this, asking more narrowly-scoped questions along the way are likely to help more.
Good luck!
Not exactly what you asked, but probably close enough could be achieved by:
installing chrome-headless
setting up nodejs + couple of modules
getting the loaded and parsed with client side events outerHTML
reading from perl code the outerHTML
as follows:
# just a perl oneliner, parsing the scrapped html and passing it to Mojo::DOM
perl -MMojo::DOM -e '$s=`node scrap-html.js`; for my $e (Mojo::DOM->new($s)->find("html body a.scroll")->each){ print $e->text}';
where the code for the scrap-html.js
// file: scrap-html.js src: https://gist.github.com/magician11/a979906401591440bd6140bd14260578
const CDP = require('chrome-remote-interface');
const chromeLauncher = require('chrome-launcher');
(async function() {
const launchChrome = () =>
chromeLauncher.launch({ chromeFlags: ['--disable-gpu', '--headless','--blink-settings=imagesEnabled=false'] });
const chrome = await launchChrome();
const protocol = await CDP({ port: chrome.port });
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
// See API docs: https://chromedevtools.github.io/devtools-protocol/
const { Page, Runtime, DOM } = protocol;
await Promise.all([Page.enable(), Runtime.enable(), DOM.enable()]);
uri = 'https://qto.fi/qto/view/readme_doc'
Page.navigate({ url: uri });
// wait until the page says it's loaded...
Page.loadEventFired(async () => {
try {
await timeout(4000); // give the JS some time to load
// get the page source
const rootNode = await DOM.getDocument({ depth: -1 });
const pageSource = await DOM.getOuterHTML({
nodeId: rootNode.root.nodeId
});
protocol.close();
chrome.kill();
console.log ( pageSource.outerHTML)
} catch (err) {
console.log(err);
}
});
})();
//eof file: scrap-html.js
example for the whole setup on ubuntu:
# start install chromium-headless
sudo apt-get update
sudo apt-get install -y software-properties-common
sudo apt-get install -y chromium-browser
sudo apt-get update
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb
apt --fix-broken install
# stop install chromium-headless
# start installing the nodejs + node modules
sudo apt install nodejs
sudo npm install -g chrome-remote-interface
sudo npm install -g chrome-launcher
export NODE_PATH=/usr/local/lib/node_modules
# stop installing the nodejs + modules

Node.js on Windows Git Bash shebang failure

Windows Git Bash specific problem...
Pretty simple script which takes some user input, and does not echo it to the output. Works fine when called like node secret.js but acts strange when called as ./secret.js, needing a ctrl+c to exit, and echoing the output as you type.
#!/usr/bin/env node
var prompt = require('prompt');
prompt.start();
prompt.colors = false;
prompt.message = '';
prompt.delimiter = '';
prompt.get([{
name: 'secret',
description: 'tell me your darkest secret: ',
hidden: true
}], function(err, result){
console.log('Hey guys! He said "' + result.secret.slice(0, 5) + '..." only kidding, I won\'t tell.');
});
What is a safe way to make script run on all platforms, including git bash?
update: added env result in case it is useful...
IEUser#ie8winxp MINGW32 ~/projects/issue (develop)
$ env
HOMEPATH=\Documents and Settings\IEUser
MANPATH=/mingw32/share/man:/usr/local/man:/usr/share/man:/usr/man:/share/man:
APPDATA=C:\Documents and Settings\IEUser\Application Data
HOSTNAME=ie8winxp
SHELL=/usr/bin/bash
TERM=xterm
PROCESSOR_IDENTIFIER=x86 Family 6 Model 23 Stepping 10, GenuineIntel
WINDIR=C:\WINDOWS
TMPDIR=/tmp
OLDPWD=/c/Documents and Settings/IEUser/projects
USERDOMAIN=IE8WINXP
OS=Windows_NT
ALLUSERSPROFILE=C:\Documents and Settings\All Users
TEMP=/tmp
COMMONPROGRAMFILES=C:\Program Files\Common Files
USERNAME=IEUser
PROCESSOR_LEVEL=6
PATH=C:\Documents and Settings\IEUser\projects\issuemd\node_modules\.bin:C:\Documents and Settings\IEUser\projects\issue\node_modules\.bin:C:\Documents and Settings\IEUser\projects\node_modules\.bin:/c/Documents and Settings/IEUser/bin:/mingw32/bin:/usr/local/bin:/usr/bin:/bin:/mingw32/bin:/usr/bin:/c/Documents and Settings/IEUser/bin:/c/WINDOWS/system32:/c/WINDOWS:/c/WINDOWS/System32/Wbem:/c/Program Files/nodejs:/c/Documents and Settings/IEUser/Application Data/npm:/usr/bin/vendor_perl:/usr/bin/core_perl
EXEPATH=C:\Program Files\Git
FP_NO_HOST_CHECK=NO
PWD=/c/Documents and Settings/IEUser/projects/issue
SYSTEMDRIVE=C:
LANG=en_US.UTF-8
USERPROFILE=C:\Documents and Settings\IEUser
CLIENTNAME=Console
PS1=\[\033]0;$TITLEPREFIX:${PWD//[^[:ascii:]]/?}\007\]\n\[\033[32m\]\u#\h \[\033[35m\]$MSYSTEM \[\033[33m\]\w\[\033[36m\]`__git_ps1`\[\033[0m\]\n$
LOGONSERVER=\\IE8WINXP
PROCESSOR_ARCHITECTURE=x86
SSH_ASKPASS=/mingw32/libexec/git-core/git-gui--askpass
SHLVL=1
HOME=/c/Documents and Settings/IEUser
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
PLINK_PROTOCOL=ssh
HOMEDRIVE=C:
MSYSTEM=MINGW32
COMSPEC=C:\WINDOWS\system32\cmd.exe
TMP=/tmp
SYSTEMROOT=C:\WINDOWS
PROCESSOR_REVISION=170a
PKG_CONFIG_PATH=/mingw32/lib/pkgconfig:/mingw32/share/pkgconfig
ACLOCAL_PATH=/mingw32/share/aclocal:/usr/share/aclocal
INFOPATH=/usr/local/info:/usr/share/info:/usr/info:/share/info:
PROGRAMFILES=C:\Program Files
DISPLAY=needs-to-be-defined
NUMBER_OF_PROCESSORS=1
SESSIONNAME=Console
COMPUTERNAME=IE8WINXP
_=/usr/bin/env
Turns out cygwin is not supported by node (and I assume git bash too).
Seems that git bash is not a real tty.
Looks like someone did something about it by bundling winpty with git bash.
Solution...
From within git bash, run winpty bash, then rest should work as expected.

Categories