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

烈酒焚心 提交于 2020-01-22 19:53:11

问题


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

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.


回答1:


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.




回答2:


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.




回答3:


There is a very easy way to load tests sequentially.

Step 1 : Set up a test script in package.json: e.g.

"scripts": {
    "test": "mocha ./tests.js"
  }

Let us assume that tests.js is a file which defines the order to execute tests.

require("./test/general/test_login.js");
require("./test/Company/addCompany.js");
...
...

So here test_login will run first and then others one by one.

Step 2: Then run tests with:

$ npm test


来源:https://stackoverflow.com/questions/43229233/how-mocha-knows-which-file-to-load-first-in-the-test-suite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!