Last Updated: September 09, 2019
·
1.223K
· gerardsans

Angular - Quick prototyping using angular-mocks

AngularJs Meetup South London Collection | this article

Angular prototyping

One of the huge benefits of Angular is that you can very quickly prototype an application or idea while still using production code.

In this protip I will provide a basic skeleton to get started with angular-mocks so you will know how to mock angular requests done with $http.

Features shown in this protip:

- setting up angular-mocks
- deciding which $http requests are mocked or not
- being able to use a basic mocked user api

A working code will be included at the end.

1) Add mock dependency

First you need to include 'angular-mocks.js' script file in your project. You can go to the angular site to find out the right version. Angular

Once that is done, you will need to add the dependency to your app.

angular.module("myapp", ['ngMockE2E'])

2) Setup mock $http routes

We will be displaying a simple list of users so we will be calling the backend with "api/users". In order to provide the actual list we will use a service.

.run(function($httpBackend, Users) {

    //mock users api
    $httpBackend.whenGET('/api/users')
      .respond( Users.get() );
    //you can mock GET, POST, HEAD, PUT, DELETE, PATCH, JSONP. See $httpBackend help.

    // allow other requests to use $http. Eg: templates
    $httpBackend.whenGET(/.tpl.html$/).passThrough();
})

3) Make request using $http

While using angular-mocks we can do the regular calls to $http as the call was being made to the real backend.

$http({method: 'GET', url: '/api/Users'}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
    $scope.users = data;
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Conclusion

With this basic setup you can concentrate in one feature at a time while not depending on a full fledged backend api. This method can also be used with ngResource as internally it relies also on $http.

Resources

ngMockE2E
$httpBackend
ngResource

Demo code: link

AngularJs Meetup South London Collection | this article