How to join tests from multiple files with Mocha.js?

Sometimes, we want to join tests from multiple files with Mocha.js.

In this article, we’ll look at how to join tests from multiple files with Mocha.js.

How to join tests from multiple files with Mocha.js?

To join tests from multiple files with Mocha.js, we can require the test file in another test.

For instance, we write

const importTest = (name, path) => {
  describe(name, () => {
    require(path);
  });
}

const common = require("./common");

describe("top", () => {
  beforeEach(() => {
    console.log("running something before each test");
  });
  importTest("a", './a/a');
  importTest("b", './b/b');
  after(() => {
    console.log("after all tests");
  });
});

to define the importTest which creates a test with describe to create a new test suite.

And we call require with path to run the tests at the given path.

Next,. we call importTest with the name of the test and path to the tests in the 2nd describe to run the tests in those files.

Conclusion

To join tests from multiple files with Mocha.js, we can require the test file in another test.