Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test 'normal' (non-Node specific) JavaScript functions with Mocha?

This seems like it should be extremely simple; however, after two hours of reading and trial-and-error without success, I'm admitting defeat and asking you guys!

I'm trying to use Mocha with Should.js to test some JavaScript functions, but I'm running into scoping issues. I've simplified it down to the most basic of test cases, but I cannot get it working.

I have a file named functions.js, which just contains the following:

function testFunction() {     return 1; } 

And my tests.js (located in the same folder) contents:

require('./functions.js')  describe('tests', function(){     describe('testFunction', function(){         it('should return 1', function(){             testFunction().should.equal(1);         })     }) }) 

This test fails with a ReferenceError: testFunction is not defined.

I can see why, because most of the examples I've found either attach objects and functions to the Node global object or export them using module.exports—but using either of these approaches means my function code would throw errors in a standard browser situation, where those objects don't exist.

So how can I access standalone functions which are declared in a separate script file from my tests, without using Node-specific syntax?

like image 766
Mark Bell Avatar asked Apr 18 '12 06:04

Mark Bell


People also ask

How do you test a single mocha test?

Run a Single Test File Using the mocha cli, you can easily specify an exact or wildcarded pattern that you want to run. This is accomplished with the grep option when running the mocha command. The spec must have some describe or it that matches the grep pattern, as in: describe('api', _ => { // ... })


1 Answers

Thanks to the other answers here, I've got things working.

One thing which wasn't mentioned though—perhaps because it's common knowledge among Noders—was that you need to assign the result of the require call to a variable, so that you can refer to it when calling your exported functions from within the test suite.

Here's my complete code, for future reference:

functions.js:

function testFunction () {     return 1; }  // If we're running under Node,  if(typeof exports !== 'undefined') {     exports.testFunction = testFunction; } 

tests.js:

var myCode = require('./functions')  describe('tests', function(){     describe('testFunction', function(){         it('should return 1', function(){             // Call the exported function from the module             myCode.testFunction().should.equal(1);         })     }) }) 
like image 135
Mark Bell Avatar answered Oct 09 '22 11:10

Mark Bell