[node.js] ReferenceError: describe is not defined NodeJs

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?

This question is related to node.js rest testing

The answer is


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


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.


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


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"
},

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

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to testing

Test process.env with Jest How to configure "Shorten command line" method for whole project in IntelliJ Jest spyOn function called Simulate a button click in Jest Mockito - NullpointerException when stubbing Method toBe(true) vs toBeTruthy() vs toBeTrue() How-to turn off all SSL checks for postman for a specific site What is the difference between smoke testing and sanity testing? ReferenceError: describe is not defined NodeJs How to properly assert that an exception gets raised in pytest?