TypeScript and Mocha Hooks

Greg Pabian
Level Up Coding
Published in
5 min readSep 20, 2021

--

As a software developer, I have always ensured the maintenance of the test architecture at all times. As a principle, I believe tests should exhibit quality on par with the production code. Now, how do we achieve that with TypeScript?

In my opinion, we need to choose a proper test framework first. I found great results with Mocha — it is flexible enough to help us leverage other libraries with it. Despite its simplicity, it supports building a respectable test architecture that fits TypeScript projects well — all by using hooks.

Photo by Jamie Matociños on Unsplash

Mocha Hooks

Mocha provides 4 types of hooks:
* beforeEach (before every particular test in a particular block gets executed),
* beforeAll (before all tests in a particular block get executed),
* afterEach (after every particular test in a particular block gets executed),
* afterAll (after all tests in a particular block get executed).

I used the word “particular” on purpose, as Mocha allows us to set up hooks on any meaningful level. As you might have figured out, tests architecture are rather global constructs — and we intend to set up hooks on the global level. To achieve that, we need to dig deeper into the test configuration.

Root Mocha Hooks

Root Mocha Hooks apply to all tests in the entire test setup. How you use them is inevitably your decision — however, I would like to give you my list of ideas. I tend to rely heavily on the proper configuration of these hooks in my tests, which offloads a lot of work for people that write tests.

Mocha Context

The Mocha Context is a mutable object available for access to each test. My idea of a test architecture in Mocha is to have the same context for each test and mutate it only using the Root Mocha Hooks. It guarantees the simplicity, order, and predictable behavior of each test.

Since Mocha.Context is a class (not an extensible interface), we should define two types — InjectableContext for properties managed by us and TestContext for all properties that end up part of the context. TestContext will be the type used by the tests. A simple snippet underneath should clear this…

--

--