Mock Angular Providers with ts-mockito

Markus Ende
Aug 31, 2018 · 1 min read

For mocking TypeScript classes I use ts-mockito. Its API is easy to use and fully takes advantage of TypeScript’s type system (plus mock setup and verification is inspired by Java’s mockito library, maybe that’s why I love it).

Creation of a simple mock object looks like this:

simple ts-mockito example

Note, that both mockService and mockServiceInstance are of type MyService! This means, that we have full IDE support with auto-completion when setting up the mock in line 2. Learn more about the API in the github repository.

When using ts-mockito for mocking Angular providers, we want to write as less code as possible (Angular’s TestBed setup is verbose enough, right?). I wrote a little helper function for this, called mockProvider:

mockProvider function and usage

It takes the service type and a callback which gets called after mock creation. This is where you setup the mock. Return value is the whole {provide: …, useFactory: …} thing that tells the Angular TestBed what it should inject as service.

Feel free to use!

Markus Ende

Written by

Freelancer, Angular Trainer & Developer, Testing enthusiast.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade