Mocha not recognizing CoffeeScript/JS test when adding programatically - javascript

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.

Related

Issue a unit test on a Gulp file using Karma & Jasmine

I wrote a unit test for a Gulp file. The test runs through karma using Jasmine Framework (safari/chrome).
Knowing that Karma runs the test file, specified in the json config file, in the browser, it should have a way to run Node's modules in the browser.
After researching, I found that by using Browserify I'll be able to require modules in the browser.
When I write this command
browserify ./Test/GulpTest.js -o ./Test/TEST.js -d
The new TEST.js seems to be big
and I run the following command to start the test on the new TEST.js
karma start karma.conf.js
I get this error:
gulp input stream
✗ should compile from ts to js TypeError: Cannot read property 'isTTY' of undefined
at Object. (/Users/Snap/Desktop/Demo App/Test/TEST.js:75226:20)
at Object.252._process (/Users/Snap/Desktop/Demo App/Test/TEST.js:75284:4)
at s (/Users/Snap/Desktop/Demo App/Test/TEST.js:1:254)
at /Users/Snap/Desktop/Demo App/Test/TEST.js:1:305
at Object.31../lib/PluginError (/Users/Snap/Desktop/Demo App/Test/TEST.js:3530:9)
at Object.239../lib/PluginError (/Users/Snap/Desktop/Demo App/Test/TEST.js:75113:21)
at s (/Users/Snap/Desktop/Demo App/Test/TEST.js:1:254)
at /Users/Snap/Desktop/Demo App/Test/TEST.js:1:305
at Object.229.deprecated (/Users/Snap/Desktop/Demo App/Test/TEST.js:74824:13)
at s (/Users/Snap/Desktop/Demo App/Test/TEST.js:1:254)
Chrome 44.0.2403 (Mac OS X 10.10.4): Executed 1 of 1 (1 FAILED) ERROR
(0.037 secs / 0.03 secs)
it("should compile from ts to js", function () {
var gulp = require("gulp");
var ts = require("gulp-typescript");
var lazy = require("gulp-load-plugins");
var fs = require('graceful-fs');
var should = require('should');
var join = require('path').join;
/*
* * * Compile Typescript to JavaScript
*/
gulp.task("ts-compiler", function () {
return gulp.src("./Test/lib/file.ts")
.pipe(lazy.typescript({
// Generates corresponding .map file.
sourceMap : false,
// Generates corresponding .d.ts file.
declaration : true,
// Do not emit comments to output.
removeComments : false,
// Warn on expressions and declarations with an implied 'any' type.
noImplicitAny : false,
// Skip resolution and preprocessing.
noResolve : false,
// Specify module code generation: 'commonjs' or 'amd'
module : "amd",
// Specify ECMAScript target version: 'ES3' (default), or 'ES5'
target : "ES5"
}))
.pipe(gulp.dest("./Test/lib/dest"));
});
gulp.start("ts-compiler", function () {
console.log("compiling...");
should.exist("./Test/lib/dest/file.js");
});
});
You can't run Gulp inside karma and jasmine—you're running it as if it is a front-end library, and it is not.
You need to use a back-end testing library. You can still use jasmine, you just have to use it through nodejs, which is how gulp runs: https://www.npmjs.com/package/jasmine
You might be interested to see how I wrote unit tests for my gulp tasks where I work: https://github.com/Lostmyname/lmn-gulp-tasks/tree/master/test

Getting started with unit testing JavaScript without a framework

I am building a JavaScript application (no framework yet, but I may move it to Backbone). I have created various classes, here's an example, chart.js:
var moment = require('moment');
var chart = {
...
getAllMonths: function(firstMonth, lastMonth) {
var startDate = moment(firstMonth);
var endDate = moment(lastMonth);
var monthRange = [];
while (startDate.isBefore(endDate)) {
monthRange.push(startDate.format("YYYY-MM-01"));
startDate.add(1, 'month');
}
return monthRange;
},
setMonths: function() {
// get data via ajax
this.globalOptions.months = this.getAllMonths(data['firstMonth'], data['lastMonth']);
}
};
module.exports = chart;
My file structure is as follows:
index.js
src/
chart.js
form.js
I import the two classes into index.js and use browserify to bundle these scripts up in order to use them in my web app.
Now I want to add tests for chart.js and form.js. I have added a new directory called test/ and empty test files:
index.js
src/
chart.js
form.js
test/
test_chart.js
test_form.js
My question now is what test_chart.js should look like in order to test the getAllMonths function, and what test runner I should use.
I've started experimenting with the following in test_chart.js:
console.log('hello world');
var chart = require('../src/chart');
var months = chart.getAllMonths('2014-02-01', '2015-03-01');
// assert if months.length != 14
But if I run this with node test/test_chart.js, I get errors about failed module imports for moment etc (shouldn't these be imported automatically with the original chart.js module?).
Secondly, what test runner could I use for this kind of simple testing? I'd like something that will automatically run everything in the test directory, and offers asserts etc.
I ended up using Mocha. It's really pretty easy:
npm install --save-dev mocha
mocha
Boom!
It automatically looks for files in the test/ folder.
Still having the problem with imports though.

Webstorm IDE and mocha tests using global.expect

I currently run the following command to run my mocha tests:
./node_modules/.bin/mocha --require ./my.js
and in the js file, I am using sinon and expect for SpyOn...
global.expect = require('must');
global.sinon = require('sinon');
How do I configure the Mocha task runner to use this external file.
Using --require ./my.js I still see ReferenceError: spyOn is not defined
Any thoughts on this?
Required modules are resolved relative to the working directory specified in "Working directory" field of Mocha Run/Debug configuration.
Here is the configuration that works for me:
working directory: C:\WebstormProjects\mocha_sinon
Mocha package: C:\WebstormProjects\mocha_sinon\node_modules\mocha
Extra options: --require ./with_req/util.js
Test directory: C:\WebstormProjects\mocha_sinon\with_req
My spec file:
var EventEmitter = require('events').EventEmitter;
var should = require('should');
describe('EventEmitter', function(){
describe('#emit()', function(){
it('should invoke the callback', function(){
var spy = sinon.spy()
, emitter = new EventEmitter;
emitter.on('foo', spy);
emitter.emit('foo');
spy.called.should.equal.true;
})
})
})
util.js;
global.sinon = require('sinon');

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

Configure a separate Grunt instance in a test

I have been writing a small grunt plugin, and now I am stuck trying to test the plugin end-to-end. What I would like to accomplish is this
Write a test case that configures a grunt instance with a minimal grunt config for my plugin and runs that task
Test that the file produced equals the intended output
Run that test automatically when running grunt nodeunit
So far, I seem stuck on configuring an individual Grunt instance, as the new instance seems to share configuration with that of the already loaded Grunt instance.
I got something like this in my plugin_test.js
var testGrunt = require('grunt');
exports.codekit = {
setUp: function(done) {
testGrunt.initConfig({
myPlugin : {
// the config
}
});
testGrunt.task.run(['myPlugin']);
done();
},
basic_parsing_works: function(test) {
test.expect(1); // no idea what this does
test.equal(1,1,'basic test');
//var actual = testGrunt.file.read('tmp/test01_result.html');
//var expected = testGrunt.file.read('expected/test01_expected.html');
//test.equal(actual, expected, 'should parse file.');
test.done();
}
};
The problem is that when I run the task for myPlugin it uses the configuration loaded in the "outer" (already running) Grunt instance. Even though I have specifically created a new Grunt instance under a different name (testGrunt).
Is there a way to avoid this?

Categories

Resources