How to use Jasmine like Mocha does on node.js - javascript

Hi there I was wondering how can I use jasmine like Mocha does w/ Chai.
So basically, in Mocha you just have to install it on node and then include it within your test files like this:
const assert = require('chai').assert;
const expect = require('chai').expect;
const should = require('chai').should();
const app = require('../app');
Then you automatically include some test and run npm run test and you can see the failing and passing test via the terminal.
While I tried to install jasmine via node using npm install jasmine --save-dev and then put the ff:
const expect = require('jasmine');
const app = require('../app');
And then tried some test:
describe('Multiply Numbers', function(){
it('should return correct output', function(){
let result = app.multiplyNumbers(2,2);
expect(result, 4);
});
});
I got the ff error:
> jasmine-test#1.0.0 test c:\xampp\htdocs\unitTesting\jasmine
> jasmine
Started
No specs found
Finished in 0.003 seconds
Any idea how can I run some test on Node js like mocha and chai does?
Also where can I find the assertion options (like expect, should..etc in chai) documentation?
PS. Here's what my package.json file:
{
"name": "jasmine-test",
"version": "1.0.0",
"description": "",
"main": "app.js",
"directories": {
"test": "test"
},
"scripts":{
"test": "jasmine"
},
"author": "",
"license": "ISC",
"devDependencies": {
"jasmine": "^2.8.0"
}
}

There is a different way to implement testing environment using Jasmine for node setup.
First Install Jasmine-node Module
npm install jasmine-node --save-dev
Create a tests directory and a spec file
mkdir tests
touch tests/myFirstTest.js
Now you can add your jasmine specs in this file, following the usual Jasmine syntax.
The documentation to be followed is here: https://jasmine.github.io/2.0/introduction.html
Add following in your spec file to integrate your app with the spec.
var myApp = require("../myApp.js")
One problem identified regarding this integration is that the specs may run again and again if server is not closed. For preventing this, just go to your application's main js file and export the close server function. Basically you need to add following in your app.js:
exports.closeServer = function(){
server.close();
};
Be sure to close the server in afterEach jasmine function (refer doc above) as follows:
myApp.closeServer();
In order to run tests from terminal using npm test, just add this to your packages.json file:
"scripts": {
"test": "jasmine-node tests"
}
You are all setup! Just run in your terminal,
npm test

Related

Jest unit test failing with `ReferenceError` from NPM package module

I'm getting failed tests after installing an NPM package (one of my own packages).
Specifically, I'm getting ReferenceError: cc is not defined, with the stack trace leading back to one of the exports in my NPM package.
cc is an object from a game framework (Cocos2d-x) that is included in my project locally.
The game framework is not included in my NPM package, but the package does reference the object with the assumption that whatever project has the package installed will also have the game framework already included. So essentially, Cocos2d-x is a peer dependency, but is not listed as one since it's not an NPM package itself.
The code I'm testing in my project does not make any reference to the game framework. And the methods that I'm importing from my NPM package do not make any reference to the game framework. I'm importing these methods using destructuring (e.g. import { helper1 } from 'my-package').
With that said, I wouldn't expect it to be an issue. But Jest doesn't like the fact that cc is referenced from an entirely different export on my NPM package (one that is not being imported into the file being tested). In other words, helper2 is causing Jest to fail because it does reference cc, but helper2 isn't being imported.
How should I go about fixing this error so that the tests pass?
I tried to recreate an environment similar to yours and I haven't been able to reproduce this error:
/so
foo/
index.js
package.json
answer.test.js
package.json
Here's the content of ./package.json:
(As you can see it has foo as a dependency)
{
"name": "so",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^24.1.0"
},
"dependencies": {
"foo": "./foo"
}
}
Here's the content of ./foo/package.json:
{
"name": "foo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT"
}
And here's ./foo/index.js:
(As you can see helper2 references a global variable that is not defined.)
module.exports = {
helper1: () => 42,
helper2: () => cc
};
Now the test file:
const {helper1} = require('foo');
test('helper1 returns the answer', () => {
expect(helper1()).toBe(42);
});
When I run the test (yarn test), the test passes with no errors or warnings. So it doesn't seem that Jest is bothered by having a method referencing a global object that is not in scope.
Perhaps you could leverage Jest configuration options:
globals
A set of global variables that need to be available in all test environments.
setupFiles
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.
In my specific case, the problem was in one of my exports from the NPM package that looks something like this:
// NOTE: cc is undefined, with assumption that any project installing the NPM package will have
// the required game framework
class BackgroundLayer extends cc.Node {}
export default BackgroundLayer;
The solution was to simply add globals to my project's Jest config, like so:
"jest": {
"globals": {
"cc": {
"Node": null
}
}
}
What is still not clear to me at this point is if this is to be expected. In other words, if Jest should be failing a unit test that has nothing to do with a non-imported export.
did you try to create a lite version ?
Lite version
there was a discussion on that in the cocos2d forum

Run Jest tests only for current folder

I have Jest installed on my machine and typing jest from terminal results in tests from parent folers also getting executed. I want to run tests only from the current folder.
For e.g. if I go to c:/dev/app in terminal and type some-jest-command, it should only run files with .test.js present in the app folder. Currently, running jest command from app folder runs tests in parent folders too, which is not my desired behaviour.
By default, Jest will try to recursively test everything from whatever folder package.json is located.
Let's say you're in c:/dev/app, and your package.json is in c:. If your basic command to invoke Jest is npm test, then try with run npm test dev/app.
If you want to run the tests from a specific folder user the --testPathPattern jest flag. When setting up the npm script add the path to the folder as well. In your package.json add the flag in you npm scripts. Check the bellow code for an example.
"scripts": {
....
"test:unit": "jest --testPathPattern=src/js/tests/unit-tests",
"test:integration": "jest --testPathPattern=src/js/tests/integration"
....
},
If you want to watch as well for changes, use the watch flag:
{
...
"test:unit": "jest --watch --testPathPattern=src/js/tests/unit-tests",
...
}
After that open, the command line, change the directory where your project is and run the unit test.
npm run test:unit
or integration tests.
npm run test:integration
To only run testing in a specific directory and to coerce Jest to read only certain type of files(my example: 'ExampleComponent.test.js' with new Jest version #24.9.0 you must write exact "testMatch" in jest.config.json || package.json in "jest" part next "testMatch": [ "<rootDir>/src/__tests__/**/*.test.js" ],
This testMatch in my case hits all files with the prefix .test.js in tests/subdirectories/ and skips all other files like 'setupTest.js' and other .js files in 'mocks' subdirectory which is placed inside of 'tests' directory,so,my 'jest.config.json' looks like this
{
"setupFiles": [
"raf/polyfill",
"<rootDir>/setupTests.js"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"moduleNameMapper": {
"^.+\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
"testMatch": [
"<rootDir>/src/__tests__/**/*.test.js"
]
}
Just adapt to your needs 'testMatch' regex.
A little note: This is for jest#24.9.0 && enzyme#3.10.0 if it matters to anyone.
I hope it will be useful to someone, cheers all.
--package.json
"scripts": {
"test": "jest"
}
--jest.config.js
module.exports = {
"testMatch": [
"<rootDir>/tests/unit/*.test.js"
]
}
From the root of your project, you can run jest <substring of files> and it will only run the test files which have the substring you added.
$ jest /libs/components
> [PASS] /libs/components/button.tsx
yarn:
yarn test nameoffolder
npm:
npm test nameoffolder
For example, if you have a folder named widget and you only want to run the tests in the widget folder you would run this command.
yarn:
yarn test widget
npm:
npm test widget

uglifyjs-folder remove console.log & alert from minified files

I am minifying multiple files in a folder using uglifyjs-folder in npm package.json like :
"uglifyjs": "uglifyjs-folder js -eyo build/js"
It is working as intended & minify all files in folder.
I want to remove any console.log & alert while minify but not able to find any option with uglifyjs-folderhttps://www.npmjs.com/package/uglifyjs-folder
Please help.
Short Answer
Unfortunately, uglifyjs-folder does not provide an option to silence the logs.
Solution
You could consider writing a nodejs utility script which utilizes shelljs to:
Invoke the uglifyjs-folder command via the shelljs exec() method.
Prevent logging to console by utilizing the exec() methods silent option.
The following steps further explain how this can be achieved:
Install
Firstly, cd to your project directory and install/add shelljs by running:
npm i -D shelljs
node script
Create a nodejs utility script as follows. Lets name the file: run-uglifyjs-silently.js.
var path = require('path');
var shell = require('shelljs');
var uglifyjsPath = path.normalize('./node_modules/.bin/uglifyjs-folder');
shell.exec(uglifyjsPath + ' js -eyo build/js', { silent: true });
Note: We execute uglifyjs-folder directly from the local ./node_modules/.bin/ directory and utilize path.normalize() for cross-platform purposes.
package.json
Configure the uglifyjs script inside package.json as follows:
{
...
"scripts": {
"uglifyjs": "node run-uglifyjs-silently"
...
},
...
}
Running
Run the script as per normal via the command line. For example:
npm run uglifyjs
Or, for less logging to the console, add the npm run --silent or shorthand equivalent -s option/flag. For example:
npm run uglifyjs -s
Notes:
The example gist above assumes that run-uglifyjs-silently.js is saved at the top-level of your project directory, (i.e. Where package.json resides).
Tip: You could always store run-uglifyjs-silently.js in a hidden directory named .scripts at the top level of your project directory. In which case you'll need to redefine your script in package.json as follows:
{
...
"scripts": {
"uglifyjs": "node .scripts/run-uglifyjs-silently"
...
},
...
}
uglify-folder (in 2021, now?) supports passing in terser configs like so:
$ uglify-folder --config-file uglifyjs.config.json ...other options...
and with uglifyjs.config.json:
{
"compress": {
"drop_console": true
}
}
And all options available here from the API reference.

Testing Typescript Generated Classes with node.js, Mocha and mocha-jsdom?

I would like to run unit tests from bash to test my Typescript generated Javascript classes using mocha and mocha-jsdom. I'm using mocha-jsdom because I want to emulate the dom in my tests but run unit tests from bash.
I've seen a few examples where they use the frontend testing framework for mocha in a browser, but I haven't seen any where they are run from bash.
It appears that I am unable to include the Javascript classes generated from Typescript in my mocha unit tests.
var jsdom = require('../../index');
require('../../src/js/acct/AccountManager.js');
describe('GenerateHTML', function() {
describe('#generateHTML()', function() {
jsdom()
it('should generate a table', function() {
var vahm = new VerticalAccountHTMLManager(document, "testId");
expect($("#testId")[0]).eql("table");
});
});
});
Is there any way to import the functions that create the classes into the mocha unit test while still running it from bash?
So let's start from executing the test.
For executing the tests you have several options:
Use karma. Karma is a JavaScript test runner. Actually you specify inside a karma.config.js file all the tests you want to execute, and it will execute all your tests. You have also a watch functionality which allows you to execute the test every time you make changes to your code
Use node.js. Inside the script property of your package.json file, you specify the command test and you associate to that script the command in order to execute mocha against all your tests. Then you can run the test just typing npm test
If you want to use a bash, my suggestion is to use it in order to trigger the npm test command or the karma command. That's the easiest way you can use for starting tests through bash. You can also setup a .bat file on Win which runs your tests always through the npm/karma commands
Use a task runner as Gulp, Grunt etc... You can specify a task where you trigger your tests and then run the task providing for example the command gulp mytask
My suggestion is to use node.js directly at the moment. It makes things easier.
About TypeScript, you can directly use mocha with TypeScrit, no need of JavaScript. I suggest you to integrate mocha with chai, chai-as-promised and sinon. Chai is an assertion library. Chai-as-promised allows you to test promises and sinon to test functions and methods.
This is an example of package.json with the test command I was saying above:
"scripts": {
"test": "find ./src -name '*spec.ts' | xargs mocha -r ts-node/register"
}
With this line, you will execute all the files which end for *spec.ts.
The ts-node is a really useful node plugin which allows you to run ts directly through the command ts-node myfile.ts
About the dependencies to include in your package.json here a useful list:
"devDependencies": {
"#types/chai": "^3.5.0",
"#types/chai-as-promised": "^0.0.30",
"#types/mocha": "^2.2.40",
"#types/node": "^7.0.12",
"#types/sinon": "^2.1.2",
"chai": "^3.5.0",
"chai-as-promised": "^6.0.0",
"husky": "^0.13.3",
"mocha": "^3.2.0",
"sinon": "^2.1.0",
"ts-node": "^3.0.2",
"typings": "^2.1.1"
}
About how to integrate mocha inside your tests, here a declaration of a spec file that you can use as patter:
// imports of testing libraries
import * as mocha from 'mocha';
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import sinon = require('sinon');
// import of the source files to be tested
import Main from './Main'; // an example
// testing inits
chai.use(chaiAsPromised);
const expect = chai.expect;
const assert = chai.assert;
const should = chai.should();
You can try to take a look to this repo. There is a really simple project with TypeScript and all the testing libraries I said above. It's still in progress and I didn't have time to finish it yet, so also the main README.md is not updated.
But if you clone the project or download the source, you can have a really panoramic of all the things I was saying above and an illustration of all the methods you can use inside your tests:
https://github.com/quirimmo/testing-typescript-mocha-chai-sinon
Hope this help! for any query let me know!

Using Travis-CI for client-side JavaScript libraries?

I'm not sure to use Travis-CI for my client-side JavaScript library or not, because it compiles with NodeJs on Travis-CI servers.
I want to know is this a good approach to use some kind of continuous integration such as Travis-CI for client-side libraries or not?
Yes of course you should use continous integration with client side libraries.
I personally use PhantomJS (headless webkit browser) which is already installed in Travis-CI. I think this is the better option for client-side stuff than NodeJs.
If you use Grunt, it gets even easier to use, all you need is a simple Gruntfile.js file, your tests that run in browser (I use QUnit), and a simple .travis.yml
Gruntfile.js:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
qunit: {
files: ['test/index.html']
}
});
// Load plugin
grunt.loadNpmTasks('grunt-contrib-qunit');
// Task to run tests
grunt.registerTask('test', 'qunit');
};
.travis.yml:
before_script:
- sudo npm install -g grunt
script: grunt test --verbose --force
You can see it in action at one of my projects (source on GitHub).
I started with the answer from Odi and moved to gulp to get it working. If you specify node_js as your language in your travis file, travis will automatically run
npm install
followed by
npm test
The first will install any devDependencies specified in a package.json file, the second will run the script named "test" also from package.json. Below you'll find the three files I needed to have in the top level of my repo for travis to run a single qunit suite.
.travis.yml
language: node_js
node_js:
- "0.10"
gulpfile.js
var gulp = require('gulp'),
qunit = require('gulp-qunit');
gulp.task('default', function() {
return gulp.src('./tests/unit/unittests_nupic-js.html')
.pipe(qunit());
});
package.json
{
"name": "nupic-js",
"version": "0.0.1",
"description": "JavaScript port of NuPIC",
"license": "GPL-3.0",
"repository": "iandanforth/nupic-js",
"bugs": { "url" : "http://github.com/iandanforth/nupic-js/issues"
},
"author": {
"name": "Ian Danforth",
"email": "iandanforth#gmail.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "gulp"
},
"keywords": [
"numenta",
"nupic",
"machine learning"
],
"devDependencies": {
"gulp-qunit": "~0.2.1",
"gulp-util": "~2.2.14",
"gulp": "~3.5.1"
}
}
Odi's answer updated and using npm to resolve dependencies:
.travis.yml
language: node_js
node_js:
- "6"
.Gruntfile.js
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
qunit: {
files: ['./test/qunit.html']
}
});
// Load plugin
grunt.loadNpmTasks('grunt-contrib-qunit');
// Task to run tests
grunt.registerTask('test', 'qunit');
};
Package.json (relevant parts)
"devDependencies": {
"grunt": "^1.0.1",
"grunt-contrib-qunit": "^1.3.0"
},
"scripts": {
"test": "grunt test"
}
You can try the configuration locally by running npm install and then npm test.
I found this example. Quite comprehensive!
https://github.com/jonkemp/gulp-qunit
run:
npm install
gulp test
It also has tasks for lint watching files, coverage reports and more.

Categories