Adding dynamic fixtures
#
PrefaceThis tutorial assumes that you have completed the "Adding static fixtures tutorial".
You have now all your static fixtures defined, but, what if you want your /api/users/:id
api url to respond with the correspondent user without the need of changing the current behavior?
This is usually not recommended, because you are going to implement almost a "real api", and maybe it should be better to shutdown the Mocks Server and connect the application to your real api, but for some special cases maybe you need to accomplish it.
Let's see how:
#
Define the initial users collectionExtract the users collection response from your static fixture, because it is going to be reused also by the dynamic fixture:
#
Add a dynamic fixtureAdd a dynamic fixture for GET
/api/users/:id
that will respond with the user with correspondent id, or a "not found" error if any user matches:
Dynamic fixtures functions are called with express "request", "response" and "next". Read the express documentation to learn more about
req
,res
,next
.
#
Add a new behaviorAdd a new behavior extending the "standard" one, and adding the getRealUser
fixture:
#
Change current behaviorNow you'll have three behaviors available: "standard", "user2" and "dynamic". Use the CLI to select the "dynamic" one.
#
Check the responsesBrowse to http://localhost:3100/api/users/1. You should see the first user:
Browse to http://localhost:3100/api/users/2. You should now see the second user:
Browse to http://localhost:3100/api/users/3:
#
PersistenceYou could add also dynamic fixtures for deleting, updating, or creating users, simply modifying the INITIAL_USERS
memory object from each correspondent response function.
Changes would be be persisted in memory while the server is running.