"describe is not defined" mocha (windows user) - javascript

i was trying to test this
var assert = require("assert");
describe("test suite math opreations",function(){
it("add of two",function(){
var a = 10;
var b = 10;
var c = a+b;
assert.equal(c,20);
});
it("sub of two",function(){
var a = 10;
var b = 10;
var c = a-b;
assert.equal(c,0);
});
it("multi of two",function(){
var a = 10;
var b = 10;
var c = a*b;
assert.equal(c,100);
});
it("division of two",function(){
var a = 10;
var b = 10;
var c = a/b;
assert.equal(c,1);
});
});
the file name is test
and changed the direction to the file in the terminal
and wrote
node test.js
and the terminal said "describe is not defined"
i tried alot of things
re install nodes and mocha
move the file to alot of folders
and finally.....i didn't solve the problem :)

You have to install mocha, and then run this test file with its binary.
You can either install it to your project dependencies with npm i -D mocha, then add a new npm script for example "test" and make it run "mocha" from your node_modules:
{
"name": "my-project",
"version": "1.0.0",
"description": "",
"scripts": {
"test": "mocha"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"mocha": "^10.2.0"
}
}
And then just use npm test, or npm run test.
or, you can install it globally on your machine with npm i -g mocha and then run
mocha instead of your node test.js command.
Please refer to: https://mochajs.org/#getting-started

Related

How to have cli-spinner run during ShellJS command exec?

I'm currently trying to make a simple command-line node program that allows for me to easily create a boilerplate for a lot of the React/Redux applications that I make. I'm using ShellJS to execute console commands (I've tried using Node's child_process, too.) The problem is getting cli-spinner to work with executing terminal commands. Here's my code:
#! /usr/bin/env node
var shell = require('shelljs');
var userArgs = process.argv.slice(2);
var folderName = userArgs[0];
var Spinner = require('cli-spinner').Spinner;
var depSpin = new Spinner('Installing dependencies.. %s');
depSpin.setSpinnerString(10);
shell.mkdir(folderName);
shell.cd(folderName);
depSpin.start();
// I expect for the spinner to start here (before the execution of the commands.)
shell.exec('npm init -y', {silent: true});
shell.exec('npm install --save babel-core babel-loader babel-preset-es2015 babel-preset-react react-dom react-redux redux webpack', {silent: true});
shell.exec('npm install --save-dev babel-preset-env webpack-dev-server', {silent: true});
depSpin.stop();
// Since ShellJS should run synchronously,
// the spinner should stop right after the last command finishes.
shell.touch('webpack.config.js');
shell.mkdir(['build', 'frontend']);
shell.cd('frontend');
shell.mkdir(['components', 'containers', 'reducers', 'store']);
shell.touch('app.js');
But when running the program, it just hangs without displaying anything while it installs the dependencies. It's the same as when the spinner code wasn't even in there. I've also tried removing the depSpin.stop(), which just makes the program hang forever on the spinner. I have a feeling that this issue is caused by a conflict between cli-spinner and ShellJS both using the terminal.
I was able to accomplish this effect by using child_process's spawn. I had to create a child_process.spawn and run all of the commands concatenated with &&. That freed up the console output to be exclusively the cli-spinner output. I then did an event handler for when the child process exited to stop the spinner.
#! /usr/bin/env node
var shell = require('shelljs');
var userArgs = process.argv.slice(2);
var folderName = userArgs[0];
var Spinner = require('cli-spinner').Spinner;
var depSpin = new Spinner('Installing dependencies.. %s');
var spawn = require('child_process').spawn;
var commandsDep = [
'cd ' + folderName,
'npm init -y',
'npm install --save babel-core babel-loader babel-preset-es2015 babel-preset-react react-dom react-redux redux webpack',
'npm install --save-dev babel-preset-env webpack-dev-server'
];
var depChild = spawn(commandsDep.join(' && '), {
shell: true
});
depSpin.setSpinnerString(18);
shell.mkdir(folderName);
shell.cd(folderName);
depSpin.start();
depChild.on('exit', () => {
depSpin.stop();
shell.exec('clear');
console.log('Installing dependencies.. ✓');
})
shell.touch('webpack.config.js');
shell.mkdir(['build', 'frontend']);
shell.cd('frontend');
shell.mkdir(['components', 'containers', 'reducers', 'store']);
shell.touch('app.js');
shell.cd('containers');
shell.touch(['AppContainer.js', 'Root.js']);
shell.cd('../reducers');
shell.touch('index.js');
shell.cd('../store');
shell.touch('configureStore.js');
Based on Owens' answer I made a helper method myself to run long commands with a spinner inline with normal shelljs commands;
const Spinner = require('cli-spinner').Spinner;
const spinner = new Spinner('installing.. %s');
spinner.setSpinnerString('|/-\\');
var spawn = require('child_process').spawn;
const longCommand = (command, onSuccess) => {
return new Promise((resolve, reject) => {
var process = spawn(command, { shell: true });
spinner.start();
process.on('exit', () => {
spinner.stop();
onSuccess();
resolve();
})
})
}
const npmInstall = async () => {
await longCommand("npm install", () => console.log(`NPM modules installed! 👍`))
// Other stuff
shell.mkdir('new')
}
npmInstall()

how to create simple nodejs script to wrap an binary/executable?

I want to create a nodejs file, that simple runs/wraps an executable binary file with all inputs and outputs.
For now at least on windows.
Why:
wanted to install an executable tool over npm install -g, to have it in console, without PATH changes. (npm global packages are included in PATH)
i used such solution:
const path = require("path");
const spawnSync = require('child_process').spawnSync;
const pathToMyExe = path.join(__dirname, 'bin', 'myfile.exe'); //just path to exe
const input = process.argv.slice(2); //minus "node" and "this js" arguments
spawnSync(pathToMyExe, input, {stdio: 'inherit'});
but for ".exe to PATH" problem, there is a simplier way (if you want windows only).
just set bin property in package.json to pathToExe.
https://docs.npmjs.com/files/package.json#bin
You can use the bin-wrapper npm package.
EDIT:
There's a better alternative called bin-manager.
Installation:
$ npm install --save bin-manager
Usage
const bmanager = require('bin-manager');
const base = 'https://github.com/imagemin/gifsicle-bin/raw/master/vendor';
const bin = bmanager('bin', 'gifsicle')
.src(base + '/macos/gifsicle', 'darwin')
.src(base + '/linux/x64/gifsicle', 'linux', 'x64')
.src(base + '/win/x64/gifsicle.exe', 'win32', 'x64')
.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');
bin.run(['--version'], (err, out) => {
if (err) {
console.log(error);
return;
}
console.log(out.stdout);
});

Load ES5 and ES6 npm modules with traceur

I'm using traceur to enable ES6 development under node.js via traceur.require.makeDefault. This works without issue.
I use Gemfury as a private npm repository, this also works. I'm creating my own npm packages using ES6. The challenge I ran into was how to support loading both ES5 and ES6 modules. The typical traceur.require.makeDefault example code block skips anything that has the node_modules directory in the path.
Here's how I solved this problem:
var fs = require('fs');
var path = require('path');
var traceur = require('traceur');
require('traceur-source-maps').install(traceur);
function find_parent_package(filename) {
var current = path.dirname(filename);
while (true ) {
var package_json = current + '/package.json';
if (fs.existsSync(package_json))
return require(package_json);
var last_slash = current.lastIndexOf('/');
if (last_slash === -1) return null;
current = current.substring(0, last_slash);
}
}
traceur.require.makeDefault(function(filename) {
if (filename.indexOf('package.json') > -1) return false;
if (filename.indexOf('node_modules') === -1) return true;
var p = find_parent_package(filename);
return p && p.es6;
});
And an example of a package.json for an ES6 module that works with the above code (some information has been removed for privacy):
{
"name": "ps-core",
"version": "0.2.0",
"private": true,
"es6": true,
"dependencies": {
"basic-auth": "^1.0.0",
"express": "^4.10.6",
"express-hal": "0.0.1",
"express-session": "^1.10.1",
"traverson": "^0.15.0"
}
}
Given a particular npm module path, this code walks up the directory tree until it finds a package.json file, reads it, and inspects the es6 key. If true, then it allows traceur to handle the file.
My question is this: Given the above implementation, is there a better way to do this?

shell command to child_process.spawn(command, [args], [options]) node.js

Basically, I just want to run rsync command on node app.
The raw rsync code is the below:
rsync -r -t -p -o -g -v --progress --delete -l -H /Users/ken/Library/Application Support/Sublime Text 3/Packages /Users/ken/Google Drive/__config-GD/ST3
Firstly, I tried
child_process.exec(command, [options], callback)
but, since the rsync output is long, the buffer exceeded.
So, I tried
child_process.spawn(command, [args], [options])
instead, and stream.pipe out.
var spawn = require('child_process')
.spawn;
var ps = spawn(command1, args1)
.stdout
.pipe(process.stdout);
Although this works as expected, it is way too hard to split every original rsync command to the spawn format. (I copied and paste the command from gRsync tool)
Is there smart way to do this?
Thanks.
Ok, here is the hack;
Escape white space of the MacDirectory in the terminal shell and javascript/node is very tricky, so I placed _#_ instead of \('\'+whiteSpace).
(function()
{
'use strict';
//,,,,,,,,,,,,,,
var parseShCmd = function(cmd)
{
var cmdA = cmd.split(/ /);
console.log(cmdA);
var cmd1 = cmdA[0];
var args1 = [];
cmdA.map(function(s, i)
{
if (i === 0)
{
console.log('-------------------'); //do nothing
}
else
{
args1[i - 1] = cmdA[i].replace(/_#_/g, ' ');
}
});
return [cmd1, args1];
};
var shCmd = 'rsync' +
' -r -t -p -o -g -v --progress --delete -l -H ' +
'/Users/ken/Library/Application_#_Support/Sublime_#_Text_#_3/Packages ' +
'/Users/ken/Google_#_Drive/__config-GD/ST3';
//var shCmd = 'ls -la';
var cmd1 = parseShCmd(shCmd);
console.log(cmd1[0]);
console.log(cmd1[1]);
console.log('==================');
var spawn = require('child_process')
.spawn;
var ps = spawn(cmd1[0], cmd1[1])
.stdout
.pipe(process.stdout);
//,,,,,,,,,,,,,,,,
}());

NPM script problems

I have a nodejs file runner.node.js.
If I run node runner.node.js it works
But if I try tu run it with npm test (it's referenced in package.json):
"test": "node ./spec/runner.node.js"
or
"test": "spec/runner.node.js"
It says that the file isn't executable:
sh: 1: spec/runner.node.js: Permission denied
npm ERR! Test failed. See above for more details.
npm ERR! not ok code 0
If I set the file as executable it then says:
spec/runner.node.js: 1: spec/runner.node.js: Syntax error: word unexpected (expecting ")")
npm ERR! Test failed. See above for more details.
npm ERR! not ok code 0
while it still runs correctly with "node spec/runner.node.js"
The file is this:
console.log("Running Knockout tests in Node.js");
var fs = require('fs');
var jasmine = require('./lib/jasmine-1.2.0/jasmine');
// export jasmine globals
for (var key in jasmine) {
global[key] = jasmine[key];
}
// add our jasmine extensions to the exported globals
require('./lib/jasmine.extensions');
// export ko globals
if (process.argv.length > 2 && process.argv[2] == '--source') {
// equivalent of ../build/knockout-raw.js
global.DEBUG = true;
global.ko = global.koExports = {};
global.knockoutDebugCallback = function(sources) {
sources.unshift('build/fragments/extern-pre.js');
sources.push('build/fragments/extern-post.js');
eval(sources.reduce(function(all, source) {
return all + '\n' + fs.readFileSync(source);
}, ''));
};
require('../build/fragments/source-references');
} else {
global.ko = require('../build/output/knockout-latest.js');
}
// reference behaviors that should work out of browser
require('./arrayEditDetectionBehaviors');
require('./asyncBehaviors');
require('./dependentObservableBehaviors');
require('./expressionRewritingBehaviors');
require('./extenderBehaviors');
require('./mappingHelperBehaviors');
require('./observableArrayBehaviors');
require('./observableBehaviors');
require('./subscribableBehaviors');
// get reference to jasmine runtime
var env = jasmine.jasmine.getEnv();
// create reporter to return results
function failureFilter(item) {
return !item.passed();
}
env.addReporter({
reportRunnerResults:function (runner) {
var results = runner.results();
runner.suites().map(function (suite) {
// hack around suite results not having a description
var suiteResults = suite.results();
suiteResults.description = suite.description;
return suiteResults;
}).filter(failureFilter).forEach(function (suite) {
console.error(suite.description);
suite.getItems().filter(failureFilter).forEach(function (spec) {
console.error('\t' + spec.description);
spec.getItems().filter(failureFilter).forEach(function (expectation) {
console.error('\t\t' + expectation.message);
});
});
});
console.log("Total:" + results.totalCount + " Passed:" + results.passedCount + " Failed:" + results.failedCount);
process.exit(results.failedCount);
}
});
// good to go
env.execute();
Add
#/usr/bin/env node
as the first line in your file. This way, when run as an executable your OS will know that it shall use Node.js to run it (to be exactly: your OS will know that it shall use the first application called node to execute your script).

Categories

Resources