Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up a RESTful backend mock with Sinon.js for an Angular.js application

I'm developing an Angular.js application that has RESTful services which extend the $resource service. This app will connect to a Java Spring application in the future, but right now I'm trying to set up an isolated mock that will serve all the necessary routes for my application from client side. I've used Sinon.js before to create a fake client side server that serves my routes when I developed other apps, using other MV* frameworks, such as Backbone.js.

It appears that unlike a "standard" ajax call for fetching JSON data, as JQuery/Backbone performs, Angular uses XHR differently, and it isn't "fooled" by Sinon's attempts of hijacking the request and responding from client side.

I tried to use $httpBackend to create fake routes with ready data, instead, but it appears this service was meant to be used only for unit testing, and not for the "staging environment" which I need to set up.

This is how my Sinon setup looks like, which works on JQuery.ajax, but not on Angular $resource, or $http:

var server = sinon.fakeServer.create();
server.respondWith("GET", /mydata/gi, [200,
    { "Content-Type": "application/json" },
    JSON.stringify({
        data: "myData"
    })
]);
server.autoRespond = true;

Any ideas to how this doesn't work with Angular? Or better yet, does anyone know how set such mocks for Angular apps?

like image 827
Naor Biton Avatar asked Oct 03 '22 00:10

Naor Biton


1 Answers

I believe the "e2e" (end to end) $httpBackend mock is exactly what you are looking for.

Quoting the docs: "For fake HTTP backend implementation suitable for end-to-end testing or backend-less development please see e2e $httpBackend mock."

"As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application is being developed with the real backend api replaced with a mock, it is often desirable for certain category of requests to bypass the mock and issue a real http request (e.g. to fetch templates or static files from the webserver)."

I also found a good article describing some elegant ways to use the fake back end in Angular.

like image 173
JD Smith Avatar answered Oct 07 '22 02:10

JD Smith