I'm facing an issue while trying to get javascript unit tests to work at the command line using qunit.
Here's some sample code to reproduce the error:
file util.js:
function abc() {
return 'abc';
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
abc: abc
};
}
file util-tests.js
var qunit = require("qunit");
test("Test abc function", function () {
equal(util.abc(), 'abc');
});
With these files, I can run tests using the following command (gives a table-like output in the shell with the test results):
qunit -c util:util.js -t util-tests.js
Now it breaks if I add the following to util.js
$(document).ready(function () {
/* some code here */
});
Here's the error output:
qunit -c util:util.js -t util-tests.js
Testing /home/mfrere/jstst/util.js ... [Error: Uncaught exception in child process.]
same problem with:
var a = $;
or:
var a = document;
So this makes me think that I need to import jQuery somehow, so I thought about adding jquery.js as a dependency to the command, like this:
qunit -c util:util.js -t util-tests.js -d jquery.js
The above command gives me the same 'Uncaught exception' error, even if util.js doesn't contain any reference to '$'.
I'll probably need to do something else to get qunit to recognize 'document' as well, but I don't know what or how.
Now here's my question: what should I do to get this to work? It is important to keep in mind I want to test my files at the command line, not in a browser.
Just in case I did something wrong in the setup process, this is how I installed node/qunit (under ubuntu):
git clone git://github.com/creationix/nvm.git ~/.nvm
in .bashrc, I added the following line:
source ~/.nvm/nvm.sh
picked a specific version of node
nvm install v0.9.2
nvm alias default 0.9
and installed qunit
npm install -g qunit
finally I had to add this in .bashrc as well:
export NODE_PATH=~/.nvm/v0.9.2/lib/node_modules
You haven't imported jQuery:
$ = require('jquery'),
jQuery = require('jquery');
If you're using browserify, change that to 'jquery-browserify'.
Related
assets/admin/js/components/formatter.js
export default function addCommas(number)
{
console.log('aaa');
return number;
}
assets/admin/js/policy_rater.js
import addCommas from 'components/formatter';
webpack.config.js
// ...
.addEntry('admin-policy', [
// './assets/admin/js/components/formatter.js',
"./assets/admin/js/policies.js",
'./assets/admin/js/policy_rater.js',
'./assets/admin/js/components/month-filter.js',
])
// ...
Running command (at least I see it in terminal, I actually run our custom command which probably calls this):
$ /app/node_modules/.bin/encore dev --watch
So very simple import. But when compiling, getting error:
I 79 files written to web/build/act
ERROR Failed to compile with 1 errors 11:20:32 AM
This dependency was not found:
components/formatter in ./assets/admin/js/policy_rater.js
To install it, you can run: npm install --save components/formatter
why it even asks me to install if it is not a third party library but just file in my codebase?
Turns out I needed to import this way:
import addCommas from './components/formatter';
:(
Grunt version:
CLI - v1.2.0
local - v1.0.1
I'm using grunt-exec to start a local DynamoDB server. I'm doing this by creating a custom function in .bashrc then calling it inside grunt-exec. I also tried explicitly creating an alias, which didn't fix it.
~/.bashrc
runDynamo () {
java -Djava.library.path=~/DynamoDBServer/DynamoDBLocal_lib -jar ~/DynamoDBServer/DynamoDBLocal.jar -sharedDb
}
Gruntfile.js
// ...
exec: {
dynamo: {
// Run DynamoDB locally at port 8000
// This alias has been set during the inital installation
command: "runDynamo"
}
}
// ...
var mode = grunt.option("mode") || "test";
grunt.registerTask("run", ["exec:" + mode]);
When I run grunt run --mode=dynamo, I get the following error in stdout:
Running "exec:dynamo" (exec) task
>> /bin/sh: 1: runDynamo: not found
>> Exited with code: 127.
>> Error executing child process: Error: Process exited with code 127.
The command works fine when used directly in bash (i.e. $ runDynamo), so I'm not sure why grunt-exec isn't working here.
I am trying to publish npm package, when i am install the package globally and try to run the cli command i get this errors:
/.nvm/versions/node/v0.12.2/bin/myPack: line 1: use strict: command not found
/.nvm/versions/node/v0.12.2/bin/myPack: line 3: syntax error near unexpected token `('
/.nvm/versions/node/v0.12.2/bin/myPack: line 3: `var _commandLineArgs = require('command-line-args');'
The top of the file that the error refer to:
'use strict';
var _commandLineArgs = require('command-line-args');
var _commandLineArgs2 = _interopRequireDefault(_commandLineArgs);
The package.json bin section:
"bin": {
"myPack": "dist/myPack.js"
}
When i am running this in my local development this works well, what is the problem?
Your script should start with a shebang line, otherwise it will be executed as a shell script (hence the errors).
Add this as first line to dist/myPack.js:
#!/usr/bin/env node
I'm using the expect.js library with my mocha unit tests. Currently, I'm requiring the library on the first line of each file, like this:
var expect = require('expect.js');
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
If possible, I'd like to remove the boilerplate require code from the first line of each file, and have my unit tests magically know about expect. I thought I might be able to do this using the mocha.opts file:
--require ./node_modules/expect.js/index.js
But now I get the following error when running my test:
ReferenceError: expect is not defined
This seems to make sense - how can it know that the reference to expect in my tests refers to what is exported by the expect.js library?
The expect library is definitely getting loaded, as if I change the path to something non-existent then mocha says:
"Error: Cannot find module './does-not-exist.js'"
Is there any way to accomplish what I want? I'm running my tests from a gulp task if perhaps that could help.
You are requiring the module properly but as you figured out, the symbols that the module export won't automatically find themselves into the global space. You can remedy this with your own helper module.
Create test/helper.js:
var expect = require("expect.js")
global.expect = expect;
and set your test/mocha.opts to:
--require test/helper
While Louis's answer is spot on, in the end I solved this with a different approach by using karma and the karma-chai plugin:
Install:
npm install karma-chai --save-dev
Configure:
karma.set({
frameworks: ['mocha', 'chai']
// ...
});
Use:
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
Thanks to Louis answer and a bit of fiddling around I sorted out my test environment references using mocha.opts. Here is the complete setup.
My project is a legacy JavaScript application with a lot of "plain" js files which I wish to reference both in an html file using script tags and using require for unit testing with mocha.
I am not certain that this is good practice but I am used to Mocha for unit testing in node project and was eager to use the same tool with minimal adaptation.
I found that exporting is easy:
class Foo{...}
class Bar{...}
if (typeof module !== 'undefined') module.exports = { Foo, Bar };
or
class Buzz{...}
if (typeof module !== 'undefined') module.exports = Buzz;
However, trying to use require in all the files was an issue as the browser would complain about variables being already declared even when enclosed in an if block such as:
if (typeof require !== 'undefined') {
var {Foo,Bar} = require('./foobar.js');
}
So I got rid of the require part in the files and set up a mocha.opts file in my test folder with this content. The paths are relative to the root folder:
--require test/mocha.opts.js
mocha.opts.js content. The paths are relative to the location of the file:
global.assert = require('assert');
global.Foo = require("../foobar.js").Foo;
global.Bar = require("../foobar.js").Bar;
global.Buzz = require("../buzz.js");
I have created simple Mocha test. It works perfectly when Node "assert" module is used. I run it from command line (Mocha is installed as a global node module):
$ mocha myTest.js
․
1 test complete (6 ms)
The script looks like this:
var assert = require("assert")
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
})
})
})
Well, I tried to add Chai instead of assert library. I installed it first:
npm install chai
So, the directory node_modules has been created in my project. Great so far. Then, I altered the script to use Chai:
var chai = require("chai");
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
[1,2,3].indexOf(5).should.equal(-1);
expect([1,2,3].indexOf(5)).to.equal(-1);
assert.equal([1,2,3].indexOf(5),-1);
})
})
});
It does not work, Mocha test fails with TypeError:
TypeError: Cannot call method 'equal' of undefined
I assume Chai did not define should so it is undefined.
How is this possible?
How can I make my tests run with Chai? I have tried to install Chai globally with no effect. I also ran the script with -r chai with no effect as well.
Apparently, Chai module is loaded, but does not define the variables (Object.prototype properties). How can I fix this?
var expect = require('chai').expect;
That will get your expect calls working. However, you also have a should call which comes from a different library entirely, so change
[1,2,3].indexOf(5).should.equal(-1);
to
expect([1,2,3].indexOf(5)).to.equal(-1);