node.js mocha fallback to debugger on uncaught error - javascript

Is there a way in node.js (ideally mocha too) to simulate the behavior of python
python -m pdb setup.py test
That will fallback to debug interface on if the program throws an uncaught exception.
EDIT
#robertklep suggested the undocumented breakOnException command which looks really awesome but not so much in practice:
test.js
var hello = {};
function testFunc () {
anotherFunct();
}
function anotherFunct () {
var b = hello.unfound;
}
testFunc();
And then it freezes at:
$ node debug test.js
< Debugger listening on port 5858
connecting to port 5858... ok
break in test.js:1
> 1 var hello = {};
2 function testFunc () {
3 anotherFunct();
debug> breakOnException
debug> c
debug> backtrace
EDIT2: test.js didn't yield an error in the first place. The above works fine.

Add this to your script:
process.on('uncaughtException', function() {
debugger;
});
And start it with node debug script.js. That will drop you into the debugger on uncaught exceptions/errors.
To get this (somewhat) working for Mocha tests, you can add the lines above and follow the instructions here (specifically installing node-inspector and starting Mocha using --debug-brk).
EDIT: the Node debugger also has the ability to break on errors/exceptions:
$ node debug script.js
debug> breakOnException
debug> c
...

Related

Error: A dynamic link library (DLL) initialization routine failed on electron but it's fine on node js

I'm trying to load a custom module in electron written in D with node_dlang package, which is fine with node, but it fails within electron.
the test with node, that runs just fine, goes like this:
const nativeModule = require('./module.node');
const assert = require('assert');
assert(nativeModule != null);
assert(nativeModule.ultimate() == 42);
But when I went to use it within electron.js, through the preload script, it returns in an error.
the preload script goes like this:
const {
contextBridge,
ipcRenderer
} = require("electron");
const nativeModule = require('./module.node');
const assert = require('assert');
assert(nativeModule.ultimate() == 42);
function pageLoaded()
{
// ...
}
window.addEventListener('DOMContentLoaded', pageLoaded);
the error when I attempt to load the module within electron application is:
A JavaScript error occured in the browser process
--------------------------- Uncaught Exception: Error: A dynamic link library (DLL) initialization routine failed.
\\?\C:\Users\001\Desktop\ele\module.node
at process.func [as dlopen] (VM70 asar_bundle.js:5)
at Object.Module._extensions..node (VM43 loader.js:1138)
at Object.func [as .node] (VM70 asar_bundle.js:5)
at Module.load (VM43 loader.js:935)
at Module._load (VM43 loader.js:776)
at Function.f._load (VM70 asar_bundle.js:5)
at Function.o._load (VM75 renderer_init.js:33)
at Module.require (VM43 loader.js:959)
at require (VM50 helpers.js:88)
at Object.<anonymous> (VM88 C:\Users\001\Desktop\ele\preload.js:6)
What's causing this and how do I fix this?
version
node version is: v14.17.0
electron.js: v13.1.1
both are 64-bit.
the module source code goes like this:
import std.stdio : stderr;
import node_dlang;
extern(C):
void atStart(napi_env env)
{
import std.stdio;
writeln ("Hello from D!");
}
int ultimate()
{
return 42;
}
mixin exportToJs! (ultimate, MainFunction!atStart);
it's compiled with dub command line. No arguments.
UPDATE 1 Do I need to rebuild this module? I found this but it didn't work for me either. I installed the electron-rebuild package by npm install --save-dev electron-rebuild and rebuild with .\node_modules\.bin\electron-rebuild.cmd -v 13.1.1 the command ran fine but I still got same error.
UPDATE 2: inside the console, I clicked in the javascript source code file link in the error message (from the exception) it points to this line of code, where there's this comment saying that:
no static exports found
what does that mean? is this related to the methods in D class? they're marked as public... not sure if related
Electron is a Windows-Application and therefore you need to remove output to std. Try to remove
import std.stdio : stderr;
and
import std.stdio;
writeln ("Hello from D!");
and retry import to Electron.
Please refer this (https://stackoverflow.com/a/74280836/9558119) post from me regarding same. Since it is electron build might be missing Visual C++ Build Environment: Visual Studio Build Tools

NodeJS, babel build -> regeneratorRuntime is not defined

This morning i got an error with my NodeJS and babel configuration and i have already find the solution but i would like to understand why it happen ?
After building my app with "babel ./src -d ./lib" and then running it with "node lib/index.js" i got this error:
ReferenceError: regeneratorRuntime is not defined
I have found where is the probleme, this is about how i declared a new function:
async function loopIntercom (conversationId, splited) {
// code..
}
After changing the declaration for this new one:
const loopIntercom = async (conversationId, splited) => {
// code..
}
Everything working fine, but why is there a problem with the first method ?

Mocha not recognizing CoffeeScript/JS test when adding programatically

I am trying to add mocha to an existing project. I have the following test just for putting things together...
assert = require('assert');
describe 'Array', ->
describe '#indexOf()', ->
it 'should return -1 when the value is not present', ->
assert.equal(-1, [1,2,3].indexOf(4));
Options...
--compilers coffee:coffee-script/register
Then I run mocha --opts ./mocha.opts src/test/coffee/test/test.coffee and I see
1 passing (6ms)
Now I try to create a runner file to handle
globFlat = require('glob-flat');
Mocha = require('mocha');
mocha = new Mocha();
files = globFlat.sync([
'src/test/coffee/test/test.coffee'
]);
mocha.addFile file for file in files
mocha.run();
And run mocha --opts ./mocha.opts src/test/mocha/mocha-runner.coffee I get
0 passing (0ms)
So why is it not finding the test?
Update
I have also converted everything over to JS to ensure it wasn't an issue with CS and I am getting the same thing...
require('coffee-script');
var globFlat = require('glob-flat');
var Mocha = require('mocha');
var mocha = new Mocha();
mocha.addFile('src/test/coffee/test/test.js');
runner = mocha.run();
console.log("Done");
It runs like this...
mocha src/test/mocha/mocha-runner.js
Done
0 passing (0ms)
Update 2
Ok so it appears I should be using node and not mocha for running it. This presents a problem as the .js version works but the .coffee version throws an error...
(function (exports, require, module, __filename, __dirname) { require 'coffee-script';
^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
Because node cannot recognize the coffeescript
I am going to post this up here as an answer, although I don't like it...
mocha-wrapper.js
require('coffee-script/register');
require('./mocha-runner.coffee');
mocha-runner.coffee
globFlat = require 'glob-flat';
Mocha = require 'mocha';
mocha = new Mocha();
files = globFlat.sync([
'src/test/coffee/test/test.coffee'
]);
mocha.addFile file for file in files
mocha.run();
I would like to avoid the multiple files but for now it looks like I am stuck :-/. That is why I am going to wait to accept my answer.

Not very helpful callstack when running a mocha test using selenium webdriverjs

When running a test in mocha using the selenium webdriver for JavaScript the call-stack it not really helpful.
As a simple example I've used the following simple test script test.js:
var webdriver = require('selenium-webdriver'),
test = require('selenium-webdriver/testing');
const TIMEOUT = 30000;
test.describe('selenium webdriverjs', function () {
var driver;
this.timeout(TIMEOUT);
test.before(function () {
driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.firefox()).build();
driver.manage().timeouts().pageLoadTimeout(TIMEOUT);
});
test.after(function () {
driver.quit();
});
test.it('error stack', function () {
driver.get('http://www.google.com');
driver.findElement(webdriver.By.id('doesnotexit'));
});
});
that generates the following error stack when (for example) run from Gulp:
selenium webdriverjs
1) error stack
0 passing (4s)
1 failing
1) selenium webdriverjs error stack:
NoSuchElementError: Unable to locate element: {"method":"id","selector":"doesnotexit"}
at new bot.Error (...\node_modules\selenium-webdriver\lib\atoms\error.js:108:18)
at Object.bot.response.checkResponse (...\node_modules\selenium-webdriver\lib\atoms\response.js:109:9)
at ...\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:379:20
at promise.Promise.goog.defineClass.invokeCallback_ (.../node_modules/selenium-webdriver/lib/goog/../webdriver/promise.
js:1337:14)
at promise.ControlFlow.goog.defineClass.goog.defineClass.abort_.error.executeNext_.execute_ (.../node_modules/selenium-
webdriver/lib/goog/../webdriver/promise.js:2776:14)
at promise.ControlFlow.goog.defineClass.goog.defineClass.abort_.error.executeNext_ (.../node_modules/selenium-webdriver
/lib/goog/../webdriver/promise.js:2758:21)
at goog.async.run.processWorkQueue (...\node_modules\selenium-webdriver\lib\goog\async\run.js:124:15)
From: Task: selenium webdriverjs error stack
at Context.ret (...\node_modules\selenium-webdriver\testing\index.js:128:10)
at callFnAsync (...\node_modules\mocha\lib\runnable.js:306:8)
at Test.Runnable.run (...\node_modules\mocha\lib\runnable.js:261:7)
at Runner.runTest (...\node_modules\mocha\lib\runner.js:421:10)
at ...\node_modules\mocha\lib\runner.js:528:12
at next (...\node_modules\mocha\lib\runner.js:341:14)
at ...\node_modules\mocha\lib\runner.js:351:7
at next (...\node_modules\mocha\lib\runner.js:283:14)
at Immediate._onImmediate (...\node_modules\mocha\lib\runner.js:319:5)
The stack consists of a series of deeply nested function in the mocha and selenium libraries of the local node_modules directory and actual test script test.js is not even part of the stack.
I'm wondering, if this is really the best information I can get from this setup if I just did something wrong?
Yes, this is really too much unnecessary and not really helpful information with all of the meaningless async traceback cruft, but the most important part of it, the webdriver error itself, is on top and is pretty self-descriptive:
NoSuchElementError: Unable to locate element:
{"method":"id","selector":"doesnotexit"}
You may try to clean up the output with the help of mocha-clean package. When applied, it should really leave the error message itself and only relevant parts of the stack trace eliminating everything mocha- and selenium-webdriver-specific:
Mocha stack traces are riddled with frames that you don't want to see,
like code from modules and Mocha internals. It strips away mocha
internals, node_modules, absolute paths (based on cwd), and other
unneccessary cruft.

Testing a node command line app with jasmine-node

How exactly would I go about testing a node-based CLI with Jasmine/jasmine-node? I have tested node modules in the past with Jasmine, which was easy, as I would merely require in the module in the spec file, initialise it and test it, but obviously that's different with a CLI. Obviously one method would be to convert it into a class and test it on its own, then convert it into a CLI, but that's not the real deal. Has anyone successfully tested a node CLI with Jasmine?
Like any good unix citizen, a node CLI app should support stdout redirection. If it does so, it then becomes pretty trivial to test it, by storing the buffer and running assertions on it when it ends. This testing strategy uses tape, but the general concepts of spawning a process and running assertions on its stdout should be transferable to another test framework.
var test = require('tape');
var spawn = require('child_process').spawn;
var path = require('path');
var read = require('fs').readFileSync;
test('binary', function (t) {
t.plan(3);
process.chdir(__dirname);
var ps = spawn(process.execPath, [
path.resolve(__dirname, '../bin/cmd.js'),
'fixture.txt'
]);
var out = '';
var err = '';
ps.stdout.on('data', function (buffer) { out += buffer; });
ps.stderr.on('data', function (buffer) { err += buffer; });
ps.on('exit', function (code) {
var expected = read('expected.txt', 'utf-8');
t.notOk(err, 'should not error');
t.equal(code, 0, 'should exit with code 0');
t.equal(out, expected, 'should perform the transform');
});
});
This CLI app takes a text file as its first parameter and runs it through a transform. All you have to do is provide a fixture and expected result and then run the test.
To run all tests in certain folder from CLI
On windows, from command prompt:
"<PATH TO NODE IF NOT IN ENV>\node.exe" "<PATH TO JASMINE-NODE MODULE>\jasmine-node\lib\jasmine-node\cli.js --verbose --test-dir <PATH TO SPECS>
Example:
"C:\Program Files (x86)\nodejs\node.exe" "c:\MyProject\node_modules\jasmine-node\lib\jasmine-node\cli.js" --verbose --test-dir c:\MyProject\Specs
Check docs on git:
https://github.com/mhevery/jasmine-node
https://github.com/mhevery/jasmine-node/wiki/Command-Line-Usage

Categories

Resources