How do I execute different Testcases with different structure through NodeJS and Mocha - javascript

How do I execute different Testcases with different structure through NodeJS and Mocha.
Moving forward I intend to integrate Selenium + NodeJS + Mocha
I have just started to explore NodeJS with Mocha and need some help.
Installed node.js:
C:\Users\AtechM_03>node -v
v6.11.2
Installed npm:
C:\Users\AtechM_03>npm -v
3.10.10
Configured nodeclipse as per this link and my Project structure looks like:
Installed Mocha at the default location (through command-line) as per this link.
C:\Users\AtechM_03>npm install -g mocha
C:\Users\AtechM_03\AppData\Roaming\npm\mocha -> C:\Users\AtechM_03\AppData\Roaming\npnode_modules\mocha\bin\mocha
C:\Users\AtechM_03\AppData\Roaming\npm\_mocha -> C:\Users\AtechM_03\AppData\Roaming\n\node_modules\mocha\bin\_mocha
C:\Users\AtechM_03\AppData\Roaming\npm
`-- mocha#3.5.3
Followed this link to write a program in NodeJS integrating Mocha.
Created a directory named test with in NodeProject space.
Within test folder created a file named test.js
Executed npm init to interactively create a package.json file.
C:\Users\AtechM_03>cd C:\Users\AtechM_03\LearnAutmation\NodeProject
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (NodeProject) test
version: (1.0.0) 1.0.0
description: test123
entry point: (index.js) test.js
test command: (mocha) mocha
git repository:
keywords:
author: debanjan
license: (ISC)
About to write to C:\Users\AtechM_03\LearnAutmation\NodeProject\package.json:
{
"name": "test",
"version": "1.0.0",
"description": "test123",
"main": "test.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjan",
"license": "ISC"
}
Is this ok? (yes)
C:\Users\AtechM_03\LearnAutmation\NodeProject>
package.json got generated within the Project Scope i.e. under C:\Users\AtechM_03\LearnAutmation\NodeProject as follows:
{
"name": "test",
"version": "1.0.0",
"description": "test123",
"main": "test.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjan",
"license": "ISC"
}
Added code to test.js as follows:
// Require the built in 'assertion' library
var assert = require('assert');
// Create a group of tests about Arrays
describe('Array', function() {
// Within our Array group, Create a group of tests for indexOf
describe('#indexOf()', function() {
// A string explanation of what we're testing
it('should return -1 when the value is not present', function(){
// Our actual test: -1 should equal indexOf(...)
assert.equal(-1, [1,2,3].indexOf(4));
});
});
//Create a test suite (group) called Math
describe('Math', function() {
// Test One: A string explanation of what we're testing
it('should test if 3*3 = 9', function(){
// Our actual test: 3*3 SHOULD EQUAL 9
assert.equal(9, 3*3);
});
// Test Two: A string explanation of what we're testing
it('should test if (3-4)*8 = -8', function(){
// Our actual test: (3-4)*8 SHOULD EQUAL -8
assert.equal(-8, (3-4)*8);
});
});
});
Executed npm test from project space which runs successfully:
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm test
> temperature#1.0.0 test C:\Users\AtechM_03\LearnAutmation\NodeProject
> mocha
Array
#indexOf()
v should return -1 when the value is not present
Math
v should test if 3*3 = 9
v should test if (3-4)*8 = -8
3 passing (18ms)
Followed this link to write a second program in NodeJS integrating Mocha.
Created a separate directory named temperature with in NodeProject space.
In the temperature directory created a file named app.js and a folder name test
Within the test folder, created a file named test.js
Moved the previous package.json to a sub-directory and executed npm init to interactively create a new package.json file again.
C:\Users\AtechM_03>cd C:\Users\AtechM_03\LearnAutmation\NodeProject
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (NodeProject) temperature
version: (1.0.0) 1.0.0
description: temp
entry point: (index.js) app.js
test command: (mocha) mocha
git repository:
keywords:
author: debanjanb
license: (ISC)
About to write to C:\Users\AtechM_03\LearnAutmation\NodeProject\package.json:
{
"name": "temperature",
"version": "1.0.0",
"description": "temp",
"main": "app.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjanb",
"license": "ISC"
}
Is this ok? (yes)
New package.json gets created as follows:
{
"name": "temperature",
"version": "1.0.0",
"description": "temp",
"main": "app.js",
"directories": {
"test": "test"
},
"dependencies": {
"g": "^2.0.1",
"selenium-webdriver": "^3.5.0"
},
"devDependencies": {
"mocha": "^3.5.3"
},
"scripts": {
"test": "mocha"
},
"author": "debanjanb",
"license": "ISC"
}
The current temperature Testcase looks like:
Tried to execute this second program through npm test from the Project space but it still executes the first program as follows:
C:\Users\AtechM_03\LearnAutmation\NodeProject>npm test
> temperature#1.0.0 test C:\Users\AtechM_03\LearnAutmation\NodeProject
> mocha
Array
#indexOf()
v should return -1 when the value is not present
Math
v should test if 3*3 = 9
v should test if (3-4)*8 = -8
3 passing (18ms)
Question :
I know my second program app.js is incomplete and executing it will show error (e.g. 0 passing (20ms)) but my app.js is not getting invoked at all.
Can someone please guide/suggest me what I am doing wrong here?
Any suggestion/guide/pointer will be helpful.
Update:
As of now my current code for app.js is incomplete and contains the following code:
cToF = function(celsius) {
if(!Number.isInteger(celsius)) return undefined;
return celsius * 9 / 5 + 32;
}
fToC = function(fahrenheit) {
if(!Number.isInteger(fahrenheit)) return undefined;
return (fahrenheit - 32) * 5 / 9;
}
As per this website I am following I expect an error as 0 passing (20ms)

You've got quite the long description but the thing I extracted from it is that you have essentially a structure like this:
NodeProject
├── temperature
│   └── test
└── test
Then you go into NodeProject and run Mocha. By default Mocha will look only for test in the same directory where it is invoked. So it won't look for temperature/test. If you want Mocha to run the tests in temperature/test you have to tell Mocha explicitly. For instance, this would work:
mocha test temperature/test
I'll address a common misconception here because I often see people make the mistake: merely using the --recursive flag is not enough. If you use this flag, then after Mocha has identified directories in which to find tests, it will look in them recursively. However, it does not change how Mocha identifies directories in which to find tests. Specifically, if you use mocha --recursive, it will still only look in test, and it will look in subdirectories of test. This won't make it look in temperature/test. If you do have subdirectories in test and temperature/test, you could do:
mocha --recursive test temperature/test

Related

How to disable "Use Strict" in Jest

I am writing some unit tests for a codebase which uses octal literals. Whenever the test is executed with npm test, a syntax error appears as follows:
Legacy octal literals are not allowed in strict mode.
I should stress that "use strict" does not appear anywhere in the source code, nor can I identify any option in package-lock.json or package.json indicating strict mode. Both JSON files were created with the npm init -y and received no further modification except the addition of:
"scripts": {
"test": "jest"
},
How can I force Jest out of strict mode in order to test code with legacy octal literals?
Per the docs:
By default, Jest will use babel-jest transformer
You can explicitly tell Jest you don't want it to try to apply any transforms by setting the following Jest configuration (e.g. in jest.config.<ext> or under $.jest in the package file):
"transform": {}
See full example below. Alternatively, you can leave Babel's transforms active but configure it with "sourceType": "script".
package.json:
{
"name": "strict-jest",
"version": "0.1.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^28.1.2"
},
"jest": {
"transform": {}
}
}
index.test.js:
it("works", () => {
expect(0100).toEqual(64);
});
Output:
$ npm t
> strict-jest#0.1.0 test
> jest
PASS ./index.test.js
✓ works (2 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.257 s
Ran all test suites.

Accessing jasmine with testRunner set to jest-circus results in: ReferenceError: jasmine is not defined

On default jest allows you to simply access jasmine globally. But as soon as you switch the testRunner to jest-circus, jasmine is undefined. Following is a minimal, reproducible example:
babel.config.js
module.exports = {
presets: [["#babel/preset-env", { targets: { node: "current" } }]],
};
jasmine.spec.js
it("check jasmine", () => {
console.log(jasmine);
});
jest.config.js
module.exports = {
rootDir: ".",
testRunner: "jest-circus/runner",
};
package.json
{
"name": "test-jest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
"jest-circus": "^26.6.3"
}
}
Running this test will cause following output:
$ npm test
> test-jest#1.0.0 test /Users/yusufaran/Projects/test/test-jest
> jest
FAIL ./jasmine.spec.js
✕ check jasmine (1 ms)
● check jasmine
ReferenceError: jasmine is not defined
1 | it("check jasmine", () => {
> 2 | console.log(jasmine);
| ^
3 | });
4 |
at Object.<anonymous> (jasmine.spec.js:2:15)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.01 s
Ran all test suites.
npm ERR! Test failed. See above for more details.
If you remove/comment the testRunner line in jest.config.js (so it fallbacks to the default runner) it works as expected.
Question
How can I access global jasmine object with testRunner set to jest-circus/runner? If I can't, why?
You can’t access jasmine when you use jest-circus. This is by design. jest-circus is a new test runner that was built from scratch. It mimics jasmine functionality for defining tests (i.e., describe, it, everything except expect assertions and spies).
If you depend on jasmine, then npm install -D jest-jasmine2 and use it in your jest config:
{
testRunner: 'jest-jasmine2'
}
Just adding testRunner: 'jasmine2' to jest.config.js did the trick for me

Cannot find modules that have been installed locally by NPM

I am working on a tool and I have installed some modules locally through NPM, and I get errors when I try to require these modules through NodeJS. I am working in Windows 10, I have already tried setting up NODE_PATH etc.
Below is the structure of my files:
->project
---->node_modules
---->src
-------->css
-------->js
----------->index.js
---->package.json
---->index.html
I populate the index.html by using index.js etc.
Below is the code of my package.json:
{
"name": "bip39",
"version": "1.0.0",
"description": "A tool for converting BIP39 mnemonic phrases to addresses and private keys.",
"directories": {
"test": "tests"
},
"dependencies": {
"bip39": "^2.6.0",
"bigi": "^1.4.2",
"create-hmac": "^1.1.7",
"nem-sdk": "^1.6.7"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/PavlosTze/bip39.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/PavlosTze/bip39/issues"
},
"homepage": "https://github.com/PavlosTze/bip39#readme"
}
Below is my require() code:
var createHmac = require("create-hmac");
var BigInteger = require("bigi");
const bip39 = require("bip39");
const nem = require("nem-sdk").default;
I have done the following steps on NPM:
1) npm init
2) npm install bip39
3) npm install nem-sdk
4) npm install bigi
5) npm install create-hmac
All these files are inside the node_modules, but still, whenever I run the code in the browser I get an 'Error: Cannot find module "bip39"', etc. for all modules.
EDIT: On another directory that I have cloned the same tool, before I merged it with another one, I get no error and everything works correctly, including the require(). etc. Do you need any of those files as well?
Can someone help me please?
try this :
rm -rf node_modules
npm install

I am getting 0 % coverage 0 SLOC in mocha code coverage using blanket

I am trying to get the code coverage in MOCHA JS test. I am using the blanket and the but I am getting 0 % coverage 0 SLOC why I am not understanding.
my package.json is
{
"name": "basics",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha && mocha test --require blanket --reporter html-cov > coverage.html"
},
"author": "",
"license": "MIT",
"devDependencies": {
"chai": "~2.2.0",
"mocha": "~2.2.4",
"blanket": "~1.1.6",
},
"config": {
"blanket": {
"pattern": ["index.js"],
"data-cover-never": "node_modules"
}
}
}
and index.js is
exports.sanitize = function(word){
return word.toLowerCase().replace(/-/g, ' ');
}
exports.testToString = function(){
return word.toLowerCase().replace(/-/g, ' ');
}
and indexSpec.js which is under test folder is
var chai = require('chai');
var expect = require('chai').expect;
var word = require('../index.js');
describe ('sanitize', function(){
it('String matching ', function(){
var inputWord = 'hello WORLD';
var outputWord = word.sanitize(inputWord);
expect(outputWord).to.equal('hello world');
expect(outputWord).to.not.equal('HELLO WORLD');
expect(outputWord).to.be.a('string');
expect(outputWord).not.to.be.a('number');
});
it('Checke hyphen ', function(){
var inputWord = 'hello-WORLD';
var outputWord = word.sanitize(inputWord);
expect(outputWord).to.equal('hello world');
});
} )
Paul is right. There is no point in using buggy library. Steps for making this code work with Istanbul:
Install Istanbul globally npm install -g istanbul
Change script section in package.json
"scripts": {
"test": "mocha",
"coverage": "istanbul cover node_modules/mocha/bin/_mocha -- -R spec"
},
Run test by typing npm test
Generage coverage report: npm run coverage
Coverage report will be available in coverage/lcov-report/index.html
Get blanket from the git repo. I don't know what's wrong with their npm package, but it didn't work for me either.
Getting the module from git repo works fine.
Make the below changes in your package.json file
"devDependencies": {
"chai": "~2.2.0",
"mocha": "~2.2.4",
"blanket": "git://github.com/alex-seville/blanket.git"
},
I had this problem and added a blanket.js file in my root directory as recommended by Neilskrijger here ... https://github.com/alex-seville/blanket/issues/361 .
I then set my blanket pattern in my package.json to '/lib' which was the root of my source code and it worked. The forward slash was required. My test script was "mocha --require blanket -R html-cov --recursive> coverage.html".
It seems like a lot of us have used the same tutorial and met the same problem.
I have tried all hints given on this page (tried with node versions: node-v4.3.1 and node-v5.7.0) + a few more without any luck
I ended up with another package Istanbul, which I should have done from the start since I normally use the stats as a indicator of which package to use (Its used by so many more users).
First try with this package and it worked :-)
I added this to the script section of package.json:
"coverage" : "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- -R spec"

Command not found after npm link

I have a small node.js app "doto" that I want to npm link, so that I can just call doto anywhere. As of my understanding all I need to do is:
mkdir doto
cd doto
npm init #call the project doto and entry point doto.js
touch doto.js #fill with some code
npm link
node doto.js works just fine, but when I link the package and try to call doto, the command is not found. The linking went fine, I had to use sudo (yes I know I should setup node a way that I do not need sudo, but for now I just want to get my feet wet)
Whenever I install a package globally, I can call it just fine.
I am running mac os 10.10.
doto.js
#!/usr/bin/env node
var path = require('path');
var pkg = require( path.join(__dirname, 'package.json') );
var program = require('commander');
program
.version(pkg.version)
.option('-p, --port <port>', 'Port on which to listen to (defaults to 3000)', parseInt)
.parse(process.argv);
console.log(program.port);
package.json
{
"name": "doto",
"version": "0.0.1",
"description": "",
"main": "doto.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"commander": "~2.7.1"
}
}
What am I missing?
I think your package.json is missing the bin section, according to the docs it should become something like:
{
"name": "doto",
"version": "0.0.1",
"description": "",
"main": "doto.js",
// specify a bin attribute so you could call your module
"bin": {
"doto": "./doto.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"commander": "~2.7.1"
}
}
So after you've run sudo npm link you can run doto from anywhere, if you want to change the name of the executable just change the key under "bin" to whatever you prefer.
I tried npm link and it still was not working from my test package.
My package.json in the linked package had "directories": { "bin": "./bin" } instead of "bin": { "etc": "./etc.js" }.
Once I changed it back to "bin": {...} it started to work in the test package.
So, although this directories: { bin: ... } setting is documented it doesn't seem to work correctly with npm link.

Categories