Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Mocha knows which file to load first in the test suite

I'm trying to learn the A Test Driven Approach with MongodB. The folder structure

enter image description here

A user.js to test in the src folder

const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const Schema = mongoose.Schema;

const UserSchema = new Schema ({
    name: String
});

const User = mongoose.model('user', UserSchema);

module.exports = User;

Content of test_helper.js

const mongoose = require('mongoose');;

mongoose.connect('mongodb://localhost/users_test');

    mongoose.connection
    .once('open', () => {
        console.log('Connected to Mongo!');
        done()}) 
    .on('error', (error) => { 
        console.warn('Warning', error);
    });

create_test.js content

const assert = require('assert');
const User = require('../src/user');

describe('Creating records', () => {

    it('Saves a user', (done) => {
        const user = new User({ name: 'Ankur' });
        user.save()
                .then(() => {
                    assert(!user.isNew);
                    done();
                });

Now when i run npm test the test are getting passed.

Connected to Mongo!
  Creating records
    √ Saves a user (779ms)

But My doubt is how does Mocha knows to run the test_helper.js file first, Everytime. (Also naming this file to any other name doesn't change the behavior).

Also i'm not using any root-level hook.

i know mocha loads files recursively in each directory, starting with the root directory, and since everything here is one directory only so its not making any difference here.

Can someone please suggest or help, how does Mocha exactly know that test_helper.js (or any filename with the same content) should be running first.

like image 931
Ankur Anand Avatar asked Apr 05 '17 10:04

Ankur Anand


2 Answers

There is no default set order to how Mocha loads the test files.

When Mocha scans a directory to find files it it, it uses fs.readdirSync. This call is a wrapper around readdir(3), which itself does not guarantee order. Now, due to an implementation quirk the output of fs.readdir and fs.readdirSync is sorted on Linux (and probably POSIX systems in general) but not on Windows. Moreover, it is possible that the sorted behavior on Linux could eventually be removed because the documentation says fs.readdir is just readdir(3) and the latter does not guarantee order. There's a good argument to be made that the behavior observed on Linux is a bug (see the issue I linked to above).

Note that there is a --sort option that will sort files after Mocha finds them. But this is off by default.

The behavior you observe is explainable not merely by loading order but by execution order. Here is what happens:

  1. Mocha loads the test files and executes them. So anything that is at the top level of your file executes right away. This means that the code in test_helper.js executes right away. Every call to describe immediately executes its callback. However, calls to it record the test for later execution. Mocha is discovering your tests while doing this but not executing them right away.

  2. Once all files are executed, Mocha starts running the tests. By this time, the code in test_helper.js has already run and your test benefits from the connection it has created.

Major warning Connecting to a database is an asynchronous operation, and currently there is nothing that guarantees that the asynchronous operation in test_helper.js will have completed before the tests starts. That it works fine right now is just luck.

If this were me, I'd either put the connection creation in a global asynchronous before hook. (A global before hook appearing in any test file will be executed before any test whatsoever, even tests that appear in other files.) Or I'd use --delay and explicitly call run() to start the suite after the connection is guaranteed to be made.

like image 112
Louis Avatar answered Sep 30 '22 16:09

Louis


It doesn't

Tests should not have a specific order. All test suites should be working as standalone agnostic to other suites. Inside the suite you can use "before" and "beforeEach" (or "after", "afterEach") in-order to create setup and teardown steps.

But if the order of the tests matters, something is broken in the design.

like image 38
eavichay Avatar answered Sep 30 '22 17:09

eavichay