How does Mocha handle imports? - javascript

I'm writing some test scripts and noticed that when I import a specific module and execute a specific function within that module, Mocha runs the entire module plus the one I have specified.
In test.js
const myModule = require('../someModule');
describe('Test',function(){
it('Should run a function in mu module',funciton(){
myModule.someFunction(test);
};
}
In myModule.js
module.exports = { someFunction };
function someFunction(someInput){
return true;
}
Now say I include a console log within my module as shown below:
module.exports = { someFunction };
console.log('Loging inside the module');
function someFunction(someInput){
return true;
}
When I run my Mocha test it will run my funciton but will also run my console.log
Can someone please explain this?

Related

export just a variable not the entire file - javascript

I am working on a project which requires to use node with ES6 alongside Mocha. So I came across a small issue, When I export a variable from one file to another, It actually exports the entire file! However I just want the variable to be exported.
Simply said, I want the updated value of x but doesn't want foo.js to run the Test Suit(function doubleX). How can I achieve this or what is wrong with my approach?
// foo.js
import {x} from './bar.js'
console.log(x);
// bar.js
export var x = 5;
// Test Suit Function
function doubleX(){
describe("Test Suit", function(){
// Few Calculations & Updated Variable
x += x;
// Some Test Case
it("Test Case", function(){
})
})
}
// Need to run test suit by bar.js not by foo.js
doubleX();
console.log(x);
Mocha scripts:
"scripts": {
"foo": "node_modules/.bin/mocha -bail --compilers js:babel-core/register -r jsdom-global/register foo.js",
"bar": "node_modules/.bin/mocha -bail --compilers js:babel-core/register -r jsdom-global/register bar.js",
}
When I use npm run foo
Actual Output:
10
10
(node:4981) DeprecationWarning: "--compilers" will be removed in a future version of Mocha; see https://git.io/vdcSr for more info
Test Suit
✓ Test Case
1 passing (8ms)
Expected Output:
10
By importing the bar.js file Node is running through the entire file.
Since you're calling the doubleX function and console.logging in bar.js, the value of x is altered and extra logs are being spit out.
Instead, you should change your doubleX function so it takes a parameter and then returns with a value of the parameter plus itself. Also you probably shouldn't call the function directly after defining it.
function doubleNum(num){
return num + num;
}
The function doubleX() is not exported you can test this by
// foo.js
import {x} from './bar.js'
console.log(x);
doubleX(); // would give error
It is being called inside bar.js hence it is executed
In your bar.js file use the following code:
var doubleX = function(x) {
x += x;
return x; // or you can return the above statement too using return x+= x;
};
doubleX(5);
module.exports = doubleX;
In your foo.js file
import {doubleX} from './bar.js'
console.log(doubleX);

How do I write unit tests for a single JS file?

I have a single js file with a function in in. I want to write unit tests for the function and deliver the tests and file to someone. It needs to be standalone.
Here is my project:
src: myFunction.js
tests: empty for now
myFunction.js:
function HelloWord() {
return 'Hello';
}
It would be great to have a test file like this:
import { func } from './myFunction.js';
describe('tests', function () {
it('returns hello', function () {
expect(func()).toEqual('Hello');
});
});
I don't know which unit test framework would be the easiest and fastest to accomplish what I need to do. The user needs to get my directory and just run the tests from the command line.
Using Mocha, a really fast set up would be:
1) Install mocha to package.json:
npm install --save-dev mocha
2)Write down the test. Let it be test.js under /tests/ , for example:
var myFunc = require('./myFunction');
var assert = require('assert');
describe('the function' , function(){
it('works' , function(){
assert.equal( myFunc() , 'hello');
});
});
3) Set up the package.json test command:
{
...
"scripts": {
"test": "node_modules/mocha/bin/mocha tests/test.js"
}
}
4) Call tests by npm test.

mochajs referenceerror when testing function not in test file

I have a mochajs test file and a javascript code file in setup as below:
/js/module/codefile.js
/js/test/testfile.js
The codefile.js contains some javascript functions eg:
function addNumbers(a, b){
return a+b;
}
the testfile.js calls functions in the codefile to test them:
describe("Add numbers test", function() {
it("checks valid result", function() {
var a = 2;
var b = 1;
var result = addNumbers(a, b);
expect(result).to.equal(3);
});
});
From the command line I cd to the js folder (parent of test and module directories) then I run mocha and get the following error: ReferenceError: addNumbers is not defined at Context <anonymous> (test/testfile.js).
I can't actually see how it could be defined as how can mocha know where this function is comming from? (NB I am using client side JS so can't use import, and havent see any way to specificy (in Mocha or Karma or JS in general) where functions are defined as you would in Python or Java). Any ideas on how I can get simple unit tests running in mocha?
I initially tried getting mocha to run in WebStorm but gave up after similar errors.
Well, the mocha command is a nodejs program. This means that you can use Nodejs's module system to load your function.
function addNumbers(a, b){
return a+b;
}
module.exports = addNumbers;
and in your test file you will have
var addNumbers = require('../module/codefile.js');
describe("Add numbers test", function() {
it("checks valid result", function() {
var a = 2;
var b = 1;
var result = addNumbers(a, b);
expect(result).toEqual(3);
});
});
However, you said that you are using your code on the front-end. Well in this case you simply check if the module object exists. If it exists that means that your file is required by mocha for unit testing.
function addNumbers(a, b){
return a+b;
}
if (module && module.exports) {
module.exports = addNumbers;
}
If you want to get rid of this nasty if's, you can bundle your modules using browserify. Browserify helps you code on the front-end using the Nodejs's module system. So your code will remain the same.

Is there a Java classpath-like feature for server-side Javascript?

When using JUnit and Maven in Java, one can have separate property files for src/main and src/test. This allows different configuration for code and tests, having Maven to manage the resources by using Java classpath.
Is there a similar way in Javascript code run by Node.js? I use Mocha for unit-testing and Grunt for task management.
Code example for script.js:
var config = require('./config/dev/app.js');
exports.getFileName = function() {
return config.fileName; // returns 'code.txt'
}
What I need is to make the script.js use different config file when being required in a test.js unit test like this:
var assert = require('assert');
var s = require('./script.js');
describe('Test', function () {
it('should use different config file', function() {
assert.equal('test.txt', s.getFileName());
});
});
Is there a way to use different configuration ./config/test/app.js in the script.js without having to alter the code of script.js? What I really try to avoid is to adjust the code to support unit tests. Instead, I want to achieve similar functionality such as mentioned Java classpath.
Please try this code.
Script.js
var config;
if(process.env.dev===true){
config = require('./config/dev/config.js');
}
if(process.env.prod===true){
config = require('./config/prod/config.js');
}
exports.getFileName = function() {
return config.fileName; // returns 'code.txt'
}
test.js
//set the environment here
process.env.dev = true;
var assert = require('assert');
var s = require('./script.js');
describe('Test', function () {
it('should use different config file', function() {
assert.equal('test.txt', s.getFileName());
});
});
I have not found any elegant solution out there on the web so I have implemented and published my own.
Check it out here: https://npmjs.org/package/app-config
Using the app-config plugin, only the script.js needs to get changed this way:
var config = require('app-config').app;
exports.getFileName = function() {
return config.fileName; // returns 'code.txt'
}
The app needs to be run this way for example
NODE_ENV=dev node script.js
NODE_ENV=unitTest mocha test.js
Depending on the NODE_ENV environmental variable, the right set of configuration files will be loaded by the app-config plugin.

Why do I see "define not defined" when running a Mocha test with RequireJS?

I am trying to understand how to develop stand-alone Javascript code. I want to write Javscript code with tests and modules, running from the command line. So I have installed node.js and npm along with the libraries requirejs, underscore, and mocha.
My directory structure looks like this:
> tree .
.
├── node_modules
├── src
│   └── utils.js
└── test
└── utils.js
where src/utils.js is a little module that I am writing, with the following code:
> cat src/utils.js
define(['underscore'], function () {
"use strict";
if ('function' !== typeof Object.beget) {
Object.beget = function (o) {
var f = function () {
};
f.prototype = o;
return new f();
};
}
});
and test/utils.js is the test:
> cat test/utils.js
var requirejs = require('requirejs');
requirejs.config({nodeRequire: require});
requirejs(['../src/utils'], function(utils) {
suite('utils', function() {
test('should always work', function() {
assert.equal(1, 1);
})
})
});
which I then try to run from the top level directory (so mocha sees the test directory):
> mocha
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Calling node's require("../src/utils") failed with error: ReferenceError: define is not defined
at /.../node_modules/requirejs/bin/r.js:2276:27
at Function.execCb (/.../node_modules/requirejs/bin/r.js:1872:25)
at execManager (/.../node_modules/requirejs/bin/r.js:541:31)
...
So my questions are:
Is this the correct way to structure code?
Why is my test not running?
What is the best way to learn this kind of thing? I am having a hard time finding good examples with Google.
Thanks...
[sorry - momentarily posted results from wrong code; fixed now]
PS I am using requirejs because I also want to run this code (or some of it) from a browser, later.
Update / Solution
Something that is not in the answers below is that I needed to use mocha -u tdd for the test style above. Here is the final test (which also requires assert) and its use:
> cat test/utils.js
var requirejs = require('requirejs');
requirejs.config({nodeRequire: require});
requirejs(['../src/utils', 'assert'], function(utils, assert) {
suite('utils', function() {
test('should always work', function() {
assert.equal(1, 1);
})
})
});
> mocha -u tdd
.
✔ 1 tests complete (1ms)
The reason your test isn't running is because src/utils.js is not a valid Node.js library.
According to the RequireJS documentation, in order to co-exist with Node.js and the CommonJS require standard, you need to add a bit of boilerplate to the top of your src/utils.js file so RequireJS's define function is loaded.
However, since RequireJS was designed to be able to require "classic" web browser-oriented source code, I tend to use the following pattern with my Node.js libraries that I also want running in the browser:
if(typeof require != 'undefined') {
// Require server-side-specific modules
}
// Insert code here
if(typeof module != 'undefined') {
module.exports = whateverImExporting;
}
This has the advantage of not requiring an extra library for other Node.js users and generally works well with RequireJS on the client.
Once you get your code running in Node.js, you can start testing. I personally still prefer expresso over mocha, even though its the successor test framework.
The Mocha documentation is lacking on how to set this stuff up, and it's perplexing to figure out because of all the magic tricks it does under the hood.
I found the keys to getting browser files using require.js to work in Mocha under Node: Mocha has to have the files added to its suites with addFile:
mocha.addFile('lib/tests/Main_spec_node');
And second, use beforeEach with the optional callback to load your modules asynchronously:
describe('Testing "Other"', function(done){
var Other;
beforeEach(function(done){
requirejs(['lib/Other'], function(_File){
Other = _File;
done(); // #1 Other Suite will run after this is called
});
});
describe('#1 Other Suite:', function(){
it('Other.test', function(){
chai.expect(Other.test).to.equal(true);
});
});
});
I created a bootstrap for how to get this all working: https://github.com/clubajax/mocha-bootstrap
You are trying to run JS modules designed for browsers (AMD), but in the backend it might not work (as modules are loaded the commonjs way). Because of this, you will face two issues:
define is not defined
0 tests run
In the browserdefine will be defined. It will be set when you require something with requirejs. But nodejs loads modules the commonjs way. define in this case is not defined. But it will be defined when we require with requirejs!
This means that now we are requiring code asynchronously, and it brings the second problem, a problem with async execution.
https://github.com/mochajs/mocha/issues/362
Here is a full working example.
Look that I had to configure requirejs (amd) to load the modules, we are not using require (node/commonjs) to load our modules.
> cat $PROJECT_HOME/test/test.js
var requirejs = require('requirejs');
var path = require('path')
var project_directory = path.resolve(__dirname, '..')
requirejs.config({
nodeRequire: require,
paths: {
'widget': project_directory + '/src/js/some/widget'
}
});
describe("Mocha needs one test in order to wait on requirejs tests", function() {
it('should wait for other tests', function(){
require('assert').ok(true);
});
});
requirejs(['widget/viewModel', 'assert'], function(model, assert){
describe('MyViewModel', function() {
it("should be 4 when 2", function () {
assert.equal(model.square(2),4)
})
});
})
And for the module that you want to test:
> cat $PROJECT_HOME/src/js/some/widget/viewModel.js
define(["knockout"], function (ko) {
function VideModel() {
var self = this;
self.square = function(n){
return n*n;
}
}
return new VideModel();
})
Just in case David's answer was not clear enough, I just needed to add this:
if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
To the top of the js file where I use define, as described in RequireJS docs ("Building node modules with AMD or RequireJS") and in the same folder add the amdefine package:
npm install amdefine
This creates the node_modules folder with the amdefine module inside.
I don't use requirejs so I'm not sure what that syntax looks like, but this is what I do to run code both within node and the browser:
For imports, determine if we are running in node or the browser:
var root = typeof exports !== "undefined" && exports !== null ? exports : window;
Then we can grab any dependencies correctly (they will either be available already if in the browser or we use require):
var foo = root.foo;
if (!foo && (typeof require !== 'undefined')) {
foo = require('./foo');
}
var Bar = function() {
// do something with foo
}
And then any functionality that needs to be used by other files, we export it to root:
root.bar = Bar;
As for examples, GitHub is a great source. Just go and check out the code for your favorite library to see how they did it :) I used mocha to test a javascript library that can be used in both the browser and node. The code is available at https://github.com/bunkat/later.

Categories

Resources