This post was written by Sagiv Frenkel.
As developers one of the first and most basic things we learn is “Don’t repeat yourself!”.
That means trying to avoid writing the same code twice – in other words, no copy paste!
While we still sin with the occasional copy paste, it’s something we’re mindful of and is easy to notice. We just have to remember to refactor later on.
But do we treat our mocking the same ?
Lets look at a typical development flow
1) Create your UI/UX, services and controller.
2) Create your server API calls.
3) Test your application, manually/automated with self generated data in different scenarios.
What’s wrong with this approach?
We are’nt repeating code, but we are repeating work
1) Documenting – there’s no good way to tell which user/data to use for which scenario.
2) Running – you need to log in/out to change users or manually change code to fit changes.
3) Testing – error scenarios, edge cases, and request delays/throttling are very hard. Using override scripts or using comments to switch data are the only tools at our disposal.
Can we do better?
Leonardo is an open sourced AngularJS module created by Outbrain. It can be installed from npm or Bower, and easily integrates into existing AngularJS applications (more details on Leonardo’s GitHub repo)
Leonardo has a fancy UI where you can easily toggle different states/scenarios.
It enables you to:
1) Centralize your mocking and scenario configuration.
2) Persist the configuration into an external file.
3) Create manual QA or automated test
We use Leonardo extensively with protractor. More on this in another post.
Want to get started with Leonardo?
Check this Example to see how you can move from a regular image gallery to a mocked one.
How does Leonardo work?
Leonardo has two important concepts – states and scenarios.
We add states to declare what and how to mock.
There are two types:
Ajax States – This it what we will typically use. We declare the url and verb we wish to mock and what response data we wish to return – including a delay and a status.
Non Ajax States – This requires more work on the part of the developers. Basically, this allows you to declare a state and its underlying data, (not mandatory) and you can later check if it’s on or off.
You can query Leonardo for the value of a certain state.
Leonardo triggers an event whenever a state changes.
Scenarios simply enable you to set a specific set of states as active.
– We currently only support Angular application. That is what we initially developed on, and was easy to implements. If the tool gains traction and popularity, it should be easy to migrate to a more vanilla approach.
– Use Leonardo to start mocking http or anything you like! We’d love to get your feedback!