This is part of a blog series – please read the intro part and install the prerequisites if you want to follow along.
Sometimes you want to start with your angular app before the backend API is written, or maybe you want to test the app and de-couple it from the real backend API.
With angular you can do this by creating a mock resource intercepts all the calls to the real back-end and returns “fake” data.
Prepare to use mocking features
To use mocking we need to prepare our app similarly to what we did for routing
- Add the angular-mocks library (using bower.json or the bower package manager)
- Add the lib/angular-mocks/angular-mocks.js script to index.html
- Add the angular-mocks typescript definition with tsd install angular-mocks –save in the package manager console
Create the Store Resource Mock
Create a new StoreResourceMock.ts file under app/common/services and add the following content
If we dissect the code we have a few different parts
- We create a new module “storeResourceMock” and inject [“ngMockE2E”] (angular mocking end to end).The reason we create a new module here is to use a neat trick… that way the only thing we need to do to use this mock in mallApp is to dependency inject it to the mallApp module.
If we don’t inject it we’ll use the real API.
- In the mockRun method we start out by preparing some fake data and store it in the stores array
- Also in the mockRun function we do routing very similarly to the routing we saw in the routing blogpost but in this case using $httpBackend.whenGET.
- when someone requests /api/stores -> respond with stores
- when someone requests /api/stores/[0-9][0-9]* i.e. /api/stores/ followed by a number with one or more digits, grab the corresponding store and return it
- when someone requests anything else in /api/ just respond with stores again (default)
- when someone requests anything in /templates/ let the request pass through
Save the file and include the script in index.html
Inject the module to use it
In order to have our calls to /api/stores/… routed to this, the only thing we need to do is inject this module into mallApp in app.ts
If you browse the site now you will notice that it is using the fake data instead… and that is all there is to mocking… pretty sweet huh?