Don Smythe
Don Smythe

Reputation: 9804

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.

Upvotes: 1

Views: 2038

Answers (1)

Andrei CACIO
Andrei CACIO

Reputation: 2119

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.

Upvotes: 4

Related Questions