Est. reading time: 3 minutes
So this is going to be a rather short one because there's really not much to it but my brain overthought the problem so hard, I had to write about it.
As I already said I recently needed to use a service inside a Storybook story. (By the way, if you haven't given Storybook a whirl, you should. It's really nice.) To give you the gist of the situation, we have a notification service that has a simple method called addNotification
which - you guessed it - adds some notifications to a list, which are then shown in the app. Pretty simple.
And as you probably know services are given to you by Angulars Dependency Injection (DI). So how do I get the service inside a storybook story where I just export some objects and functions? ๐ค
So I searched around and found multiple things like ReflectiveInjector.resolveAndCreate()
or creating another component that had a static instance of the root AppInjector
, which I could then fetch from there and get my service using AppInjector.get(MyService);
.
๐
It cannot be that hard, can it?
๐๐๐
So I searched some more and then it hit me. Why am I fighting the framework? Why am I not simply using the tools that Angular already hands me?
So the VERY simple solution to my problem is a wrapper component. Yeah, that's it. A simple component, that wraps my component I want to test inside storybook.
@Component({ template: ` <mimo-big-button (onClick)="notify()"> Trigger Notification</mimo-big-button > <label> Notification Type <select [(ngModel)]="selectedValue"> <option value="success">success</option> <option value="info">info</option> <option value="warning">warning</option> <option value="error">error</option> </select> </label> <mimo-notification-list></mimo-notification-list>`,})class NotificationListWrapperComponent { selectedValue: NotificationType = 'success';
constructor(private notificationService: NotificationService) {}
notify() { this.notificationService.addNotification(...); }}
Using the wrapper component I can add the required service in the constructor, let Angular do its thing and voilรก - I have everything I wanted.
So I guess the moral of the story here is, that sometimes (probably not only sometimes, lol ๐คทโโ๏ธ ) I should simply take a step back and think it through before instantly heading off into the depths of Stackoverflow.