Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Mocha's basic functions 'describe/before/it' implemented?

I'm somewhat new to JS, very new to Mocha, so I apologize if this is a dumb question...

I recently started working with Mocha as I'm in the early stages of a new side-project. I have mocha installed locally by the way, npm i mocha --save-dev.

I start considering if I should implement portions of my project like mocha, since I'm so happy with how easy it is to get going. Trouble is I can't figure out how they have this set up. I've looked through some of the code on GitHub, but would like a high level summary.

This is my test.js file

const app = require('../src/app');
const assert = require('assert');

describe('my app', function(){

    it('does something cool', function(){
        assert.strictEqual(app.foo(), true);
    })
});

I'm confused because I don't have const mocha = require('mocha'); in there but VS Code still recognizes identifiers like describe before, and it. VS Code even tells me when I hover on describe that it's var describe: Mocha.SuiteFunction.

How is this code working, let alone with IntelliSense? I was expecting to have to do something like mocha.describe().

like image 911
scottmwyant Avatar asked Sep 16 '25 07:09

scottmwyant


1 Answers

As mocha loads the test files, it adds it to the global context.

  • Seen here: suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self) (note the global argument here),
  • Handled here: suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) {}) (note that context is global from suite.emit)

VS Code even tells me when I hover on describe that it's var describe: Mocha.SuiteFunction

Your project probably has @types/mocha package installed. Intellisense didn't come up for me until I ran npm install --save-dev @types/mocha.

like image 120
Soc Avatar answered Sep 19 '25 15:09

Soc