Full Backend Mock With Angular Js

If you ever developed a multi-layered web application, you might had to wait for backend to be in line with your client application, or some sysadmin to stop slacking… or anything else, really.
While waiting for someone or something to work you might have lost people interest, or have missed a client’s demonstration…fear not!
If you are using AngularJS, the good news is that you have a workaround to make things appear to work :)

ngMockE2E

First thing, you will need to include ngMockE2E module in your application.
Since the Angular’s modularized nature you can include a specific mock module in your application, and when the backend is ready to work, just remove the
module inclusion, it will work with your true backend with no additional coding!

NOTE: the module to use for mocking is ngMockE2E not ngMock.
The former only mocks the $httpBackend service, and auto-responds to requests, that’s exactly why we want to use it!

A little example about how it works:

view full gist here

plunker working demo

As you can see ngMock require a synchronous return object, there’s no workaround for this, it’s desiged for testing, and for simplicity.
Although you can access/write localStorage, SQlite or indexedDB synchronously, so you’ve many opportunities to manipulate data.

Some outdated table about browser support

While i don’t see many limits with this, sometimes you’ll want to simulate a true backend, with the classic delays that suits a true AJAX response.
They were invented to be slow after all, otherwise they would be synchronous

The next level, delay.

ngMock of course isn’t thinked with delay support, some brilliant guy made a decorator to delay all the responses, but i wanted to do more.
In a public project that i’m developing, i needed xhr request abortion, that of course isn’t supported in mocking; in other words every request made gets completed, no matter what

But we can simulate angular.js behaviour with a simple $http interceptor:

Possibilities here are vast, randomize timeout, simulate packet drops, authentication simulation, many ideas can take life with just those simple pieces of code.

plunker live demo with random delay

I hope some hackers love this flexibility as much as i do, happy coding!