Our last newsletter covered how to generate mock data for our Angular applications with Mockaroo.
Today, we’ll cover how to use that data in our apps so it can:
- Act as a temporary backend implementation so you can build your Angular components before the backend API is ready.
- Use that data as mocks for your unit tests.
Using hard-coded data in our Angular apps
Let’s say we need to display a list of users in a component, but the backend doesn’t have that data ready yet, or we want to try it with fake data. We head to Mockaroo, generate a JSON file with 100 users, and then copy-paste that JSON string and assign it to a constant in our code (example here – all links in the rest of this post go to the source code of the mentioned file as well):
Then we want to access that data using a service. We already have a UserService
that’s using our backend, but we want to replace that call with our fake data:
So we generate a new FakeUserService that has the same shape as UserService
, but is returning a custom Observable of our mock data instead of making an HTTP request:
Finally, we change the dependency injection configuration in our AppModule
so that the application uses FakeUserService
instead of UserService
:
And now, our AppComponent
believes it’s using a real UserService
, but is actually getting a FakeUserService
from the Angular injector:
What’s nice and clean about that approach is that you don’t have to change any of your components. The only line of code to change to enable/disable your mock data is the providers
config in AppModule
. That’s it! You can access the entire code for this example on Stackblitz.
Using that same hard-coded data in our unit tests
Once you follow the above approach, using that data in your unit tests will be very similar. We can reuse that same FakeUserService
by configuring the Angular TestBed
in our unit tests as follows: