Mock Angular Providers with ts-mockito
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:
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:
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!
