how do I test a basic javascript file with mocha?
Problem
I'm missing something obvious here with Mocha and Coffeescript/Javascript.
I've got a file in /static/js/
called ss.coffee
, it's very simple, just one function:
function sortRowCol(a, b) {
if (a.r == b.r)
if (a.c == b.c)
return 0;
else if (a.c > b.c)
return 1;
else return -1;
else if (a.r > b.r)
return 1;
else return -1;
}
The function works correctly, but I decided I needed to start testing this project today, so I put in a mocha test file:
require "../static/js/ss.coffee"
chai = require 'chai'
chai.should()
describe 'SS', ->
describe '#sortRowCol(a,b)', ->
it 'should have a sorting function', ->
f = sortRowCol
debugger
console.log 'checking sort row'
f.should.not.equal(null, "didn't find the sortRowCol function")
describe 'sortRowCol(a, b)', ->
it 'should return -1 when first row is less than second', ->
a = {r: 2, c: "A"}
b = {r: 1, c: "A"}
r = sortRowCol a, b
r.should.equal(-1, "didn't get the correct value")
Something isn't right, because my results are:
$ mocha --compilers coffee:coffee-script ./test/ss.coffee -R spec
SS
#sortRowCol(a,b)
1) should have a sorting function
sortRowCol(a, b)
2) should return -1 when first row is less than second
× 2 of 2 tests failed:
1) SS #sortRowCol(a,b) should have a sorting function:
ReferenceError: sortRowCol is not defined
It's finding the file correctly, because it will error with 'Cannot find module' if I change that to a non-existent file name.
I tried changing sortRowCol(a,b)
to #sortRowCol(a, b)
and vice versa, didn't help. The docs (link) don't really explain what that # is doing there, is that just a ruby idiom that's here for some reason?
There must be something wrong with how I'm referencing the ss.coffee file, but I don't see it.
Solution
By require
ing the script in Node, it'll be treated as any other module, isolating sortRowCol
as a local within a closure. The script will have to use exports
or module.exports
to make it available to mocha
:
function sortRowCol(a, b) {
// ...
}
if (typeof module !== 'undefined' && module.exports != null) {
exports.sortRowCol = sortRowCol;
}
ss = require "../static/js/ss.coffee"
sortRowCol = ss.sortRowCol
# ...
As for...
The docs (link) don't really explain what that # is doing there, [...]
AFAIK, a #
is typically used to imply that it's a method -- e.g., Constructor#methodName
. Not really sure if that applies here, though.
Discussion
View additional discussion.