Does anyone have an idea how to mock $httpBackend in angular e2e tests? The idea is stubbing XHR requests while running tests on travis-ci. I\'m using karma to proxy assets
Mocking out your backend is an important step in building a complex Angular application. It allows testing to be done without access to the backend, you don't test things twice and there are less dependencies to worry about.
Angular Multimocks is a simple way to test how your app behaves with different responses from an API.
It allows you to define sets of mock API responses for different scenarios as JSON files.
It also allows you to change scenarios easily. It does this by allowing you to compose “scenarios” out of different mock files.
After adding the required files into your page, simply add scenario
as a dependency to your application:
angular
.module('yourAppNameHere', ['scenario'])
// Your existing code here...
Once you have added this to your app you can start to create mocks for API calls.
Lets say your app makes the following API call:
$http.get('/games').then(function (response) {
$scope.games = response.data.games;
});
You can create a default
mock file:
Example of someGames.json
{
"httpMethod": "GET",
"statusCode": 200,
"uri": "/games",
"response": {
"games": [{"name": "Legend of Zelda"}]
}
}
When you load your application, calls to /games
will return 200
and {"games": [{"name": "Legend of Zelda"}]}
Now lets say you want to return a different response for the same API call, you can place the application in a different scenario by changing the URL e.g. ?scenario=no-games
The no-games
scenario can use a different mock file, lets say one like this:
Example of noGames.json
{
"httpMethod": "GET",
"statusCode": 200,
"uri": "/games",
"response": {
"games": []
}
}
Now when you load your application, calls to /games
will return 200
and {"games": []}
Scenarios are composed of various JSON mocks in a manifest like this:
{
"_default": [
"games/someGames.json"
],
"no-games": [
"games/noGames.json"
]
}
You can then exclude the mock files and strip the scenario
dependency in your production app.