Angular Testing Snippets: @NgModule providers

Writing spec files for Angular Modules and exported providers

David
Sparkles Blog
2 min readMay 15, 2017

--

At my employer, we’re writing a lot of feature modules for Angular app developers. Such typical features are authentication, analytics, and other cross-cutting concerns shared across a multitude of apps.

We like “ready-made” Angular Modules that our developers can use them with one-liner statements like imports: [ FeatureModule.forRoot() ]. Then, we face a question: can we write test specifications to assert the public contract of an @NgModule({..})?

Here is one simple recipe asserting an @NgModule who implements the common forRoot() pattern. First, the spec for FeatureModule:

Further down the spec file, we’re asserting FeatureModule.forRoot():

Why are we doing this?

We asked ourselves: “how can we make sure that our module works for everyone?”

In view of this, the above tests ensure providers are set-up properly and help us to maintain stability of Angular Modules! Spec files are written in Jasmine and executed with Karma on CI runners — that is: plain-old Angular testing.

App developers shouldn’t have to care how implementation details work behind the scenes. Do they really need to know every detail about, say the authentication flow? Probably not — we, library authors, should allow them to spent their time and energy on implementing new app features. They import a feature module and we have a responsibility to make sure it works for them!

--

--