209

I am trying to define some endpoints and do a test using nodejs. In server.js I have:

var express = require('express');
var func1 = require('./func1.js');
var port = 8080;
var server = express();

server.configure(function(){
  server.use(express.bodyParser());
});

server.post('/testend/', func1.testend);

and in func1.js:

    var testend = function(req, res) {
           serialPort.write("1", function(err, results) {
           serialPort.write("2" + "\n", function(err, results) {
           });
      });
   });
    exports.testend = testend;

Now in test.js I am trying to use this endpoint:

var should = require('should');
var assert = require('assert');
var request = require('supertest');
var http = require('http');
var app = require('./../server.js');
var port = 8080;

describe('Account', function() {
        var url = "http://localhost:" + port.toString();
        it('test starts', function(done) {
                request(url).post('/testend/')
                // end handles the response
                .end(function(err, res) {
                        if (err) {
                                throw err;
                        }
                        res.body.error.should.type('string');
                        done();
                });
        });
});

But when I run node test.js I am getting this error:

describe('Account', function() {
^

ReferenceError: describe is not defined
    at Object. (/test/test.js:9:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

How can I fix the issue?

N34
  • 2,153
  • 2
  • 11
  • 7
  • 1
    What do you expect `describe()` to be and where is it defined? In looking at your test.js file, there is no symbol `describe` that is being defined there. – jfriend00 Feb 08 '15 at 23:13
  • 2
    describe() is part of Jasmine. – Keith Tyler Jun 30 '16 at 23:24
  • 1
    The documentation gap that led to this question was fixed in [November 2016](https://github.com/mochajs/mocha/commit/57dfe4ff2d6da287593a8978c121df8db90a3e23), but probably only made it to the website recently with the release of version 4.1.0. – devius Jan 21 '18 at 18:58

9 Answers9

245

Assuming you are testing via mocha, you have to run your tests using the mocha command instead of the node executable.

So if you haven't already, make sure you do npm install mocha -g. Then just run mocha in your project's root directory.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • 18
    What if I want to make the mocha functions available to node? – abhisekp Sep 08 '15 at 12:20
  • 13
    The mocha docs at http://mochajs.org/ singularly fail to mention this... – Richard Ev Aug 31 '16 at 15:39
  • 5
    no need for global mocha install, just use `"test": "./node_modules/.bin/mocha -V"` in scripts section of package.json and install mocha as one more dependency – Lukas Liesis Sep 20 '16 at 06:40
  • 3
    @LukasLiesis no need for `./node_modules/.bin`, this path is already loaded when you use `npm run` or `yarn`, so just "test": "mocha -V" will suffice – Felipe Sabino Mar 09 '17 at 22:32
  • @FelipeSabino thanks for pointing this but when you have just `mocha -V` it's not clear if it was loaded from global or local that's why i still prefer to show the path even if it's not required by the system – Lukas Liesis Mar 10 '17 at 11:13
  • after ensuring that you do have npm and mocha installed and available in your project, make sure your test file is in a folder named `test` then run this command on terminal `npm test` – Sidrah Madiha Siddiqui May 03 '21 at 12:24
215

if you are using vscode, want to debug your files

I used tdd before, it throw ReferenceError: describe is not defined

But, when I use bdd, it works!

waste half day to solve it....

    {
      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
      "args": [
        "-u",
        "bdd",// set to bdd, not tdd
        "--timeout",
        "999999",
        "--colors",
        "${workspaceFolder}/test/**/*.js"
      ],
      "internalConsoleOptions": "openOnSessionStart"
},
nuclear
  • 3,181
  • 3
  • 19
  • 38
  • 1
    This is also true for WebStorm (which is strange) – yentsun Jul 07 '19 at 09:57
  • 1
    Where exactly should I put this? – brunoparga Sep 22 '19 at 02:33
  • 5
    Thanks for the answer, made everything work!! How does this work though? How does changing tdd to bdd fix the problem? – TedTran2019 Oct 31 '19 at 20:24
  • 12
    bdd vs tdd is the 'test style' passed to mocha via command arguments, bdd is the default, but the vscode generated template uses tdd. You are probably using bdd, as most of the getting started guides use bdd. Why vscode uses tdd as the default, when bdd is the default, is beyond me. – Ryan Leach Feb 19 '20 at 12:42
  • 1
    Thanks! This was working with "tdd" but mysteriously broke after an update. Now I have to go through and remove all those "console.logs()" :) – TreeAndLeaf Oct 04 '20 at 05:51
  • Hi, I wish to know where to include the files and the file name ? – Sucheta Shrivastava Nov 30 '20 at 01:56
  • Thank you. I am new to NodeJs and VsCode and debugging legacy 4.6.2 node code you just helped me very much. Thank you – Peter Delaney Jul 30 '21 at 10:16
55

To run tests with node/npm without installing Mocha globally, you can do this:

• Install Mocha locally to your project (npm install mocha --save-dev)

• Optionally install an assertion library (npm install chai --save-dev)

• In your package.json, add a section for scripts and target the mocha binary

"scripts": {
  "test": "node ./node_modules/mocha/bin/mocha"
}

• Put your spec files in a directory named /test in your root directory

• In your spec files, import the assertion library

var expect = require('chai').expect;

• You don't need to import mocha, run mocha.setup, or call mocha.run()

• Then run the script from your project root:

npm test
cantera
  • 24,479
  • 25
  • 95
  • 138
  • 7
    In your test line, you no longer have to point to the mocha bin folder, just put `mocha`, it'll work. – Adrian Lynch Nov 30 '15 at 14:58
  • 1
    If you'd like this command to run all tests in the '/test' directory, including sub-directories, then put `mocha --recursive` – Luke Gallione Mar 03 '17 at 22:56
  • 1
    @AdrianLynch: It's been two years, but something's different or changed. No biggee, but maybe it'll help someone. I'm on Windows 10 with Mocha 4.01 installed globally. I have to point to mocha\bin\mocha, like cantera's note says. – BaldEagle Nov 28 '17 at 21:16
  • For me to work I had to include the target folder like this: `{"scripts": { "test": "node ./node_modules/mocha/bin/mocha --recursive test" }}` – Alwin Kesler Feb 06 '19 at 23:45
31

You can also do like this:

  var mocha = require('mocha')
  var describe = mocha.describe
  var it = mocha.it
  var assert = require('chai').assert

  describe('#indexOf()', function() {
    it('should return -1 when not present', function() {
      assert.equal([1,2,3].indexOf(4), -1)
    })
  })

Reference: http://mochajs.org/#require

subhojit777
  • 586
  • 3
  • 11
  • 28
  • From the ref > The require interface cannot be run via the node executable, and must be run via mocha. The question is asking about running via node. – eighteyes Jul 24 '17 at 16:32
  • 1
    I'm writing later and having different experience. In case it helps someone ... I'm on Windows 10 with mocha 4.01 and chai 4.1.2 installed globally. I don't need the first three variables here; I need the fourth. @eighteyes: I haven't found how to run Mocha directly. I'm running via "node ". – BaldEagle Nov 28 '17 at 21:35
  • 1
    `var mocha = require('mocha') var describe = mocha.describe var it = mocha.it` this is actually redundant. You can `var {describe, it} = require('mocha')` with ES6 [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) – zypA13510 Aug 23 '18 at 01:32
11

i have this error when using "--ui tdd". remove this or using "--ui bdd" fix problem.

GraySe7en
  • 182
  • 2
  • 10
7

OP asked about running from node not from mocha. This is a very common use case, see Using Mocha Programatically

This is what injected describe and it into my tests.

mocha.ui('bdd').run(function (failures) {
    process.on('exit', function () {
      process.exit(failures);
    });
  });

I tried tdd like in the docs, but that didn't work, bdd worked though.

eighteyes
  • 1,306
  • 1
  • 11
  • 18
  • Thank you very much! While I'm aware that `describe` is only available with BDD and not available for 'TDD', somehow in the setup script, I used TDD & kept thinking that I configured as 'BDD'. Internet search is of no help, as my perception was that, I did correct setup (BDD), but still I get error. It's only your solution, (which is unique from any other solutions found on Internet search results) made me add additional code that overrode my wrong setting and finally worked. Its only during other configuration setup, I saw my typo & after correcting it to 'BDD', above code was not required. – VanagaS Sep 13 '19 at 20:28
5

for Jest you have to add "jest": true to .eslintrc

{
  "env": {
    "browser": true,
    "es6": true,
    "jest": true
  },
...
Dmitry Grinko
  • 13,806
  • 14
  • 62
  • 86
2
  • Make sure you have a folder named as test that contains your test.js file.
  • Also make sure you have mocha available in your project by running mocha -version in terminal (at project path)
  • Make sure your project has package.json available, if not run npm init -y
  • And finally to run mocha test scripts, on terminal (on project path) run npm test
0

In my case it was only an issue with the linter, so I created a file in the root folder, in this case to use Chai

{
    "env": {
        "browser": true,
        "node": true,
        "chai": true
    }
}
pedrommuller
  • 15,741
  • 10
  • 76
  • 126