How to separate mocha tests in multiple files
- Introduction
- Step 1. Understand mocha hooks
- Step 2. Create a test module
- Step 3. Setup our test folder structure
- Conclusions
Introduction
One of my latest tasks was to unit test a central module in our application; there were some tests but not as many as needed. We go for at least 75% code coverage.
The most significant issues were that the test file rapidly grew up to 2000 lines of code which is unacceptable. Maintaining large files of code is an arduous task.
We concluded that we need to separate our test suite in multiple files.
The source code for the following tutorial can be found at mocha-tutorial
Step 1. Understand mocha hooks
For this study, we are creating a small project to have a better feeling how mocha loads the before
and after
hooks.
Let's create a small test case with the following structure:
- hooks/
- first/
before-first.ts
- second/
before-second.ts
some.test.ts
before-hooks.ts
Source code for before-hooks.ts
Source code for before-first.ts
Source code for before-second.ts
Source code for some.test.ts
After we compile and run the code with mocha ./dist --recursive
we receive the following result:
We noticed that mocha supports multiple
before
hooks and they run first in the order of the folder structure.
This means that we can set up our system in the
before
hooks and use it in the child folders.
Step 2. Create a test module
The following code represents our module to be tested.
Dependency1
and Dependency2
are just 2 empty classes as following:
Step 3. Setup our test folder structure
The test folder structure will be the following
- test/
- lib/
- subject/
- suites/
first.test.ts
second.test.ts
third.test.ts
index.ts
before-subject.ts
The source code for before-subject.ts
The source code for first.test.ts
So to wrap our test the source code for index.ts
When we build and run our unit tests we will receive something like:
Conclusions
- Mocha supports multiple
before/after
hooks in child folders also. - We can set up our test class in
before
hooks by attaching to thethis
instance, and we will be able to extract it init
functions atthis.test.ctx