How do I fake backend in AngularJS?

My angular application communicates with my server through the REST API. I want to mock this API in order to quickly develop the interface.

There are two approaches that I see:

  • Use ngMockE2E $ httpBackend . This requires:

    • deploying a simple static file server (e.g. python -m SimpleHTTPServer )
    • Download angular -mocks.js in my client
    • Configure mock $httpBackend to return what I want.

    Disadvantages: you need to have client-side logic that determines whether to use the layout or not. Also, it doesn't scoff at the actual $ httpRequests, and we can get confused with all flush () calls.

  • Create the actual layout. For instance. deploy a very simple node.js server that will respond to actual xhr requests.

    Disadvantages:?

ngMockE2e $ httpBackend seems like others are using, but I'm not sure why. Having a real (mock) backend seems to be a simpler and less likely cause of development errors.

+4
source share
4 answers

Just create a .json file next to your index.html . Make a $http request to get this json file that contains the data returned by your backend. This is the easiest way to mock your backend. Of course, I assume that you are serving the angular app through a web server. If you are not using a web server yet, this solution will not work.

During production, you can simply replace the url for this json file with the actual REST endpoint.

0
source

I had a similar problem, and I started with a simple .json file, as ganaraj suggested, but switched to a simple node.js server when I needed to test the data modification.

ngMockE2e is really used for testing and is not intended to actually serve a RESTful server. In the example from the link you provided, if you want to run GET for a specific phone, you will need to go through the array of phones to find the one you need.

0
source

A similar question will be answered here .

Basically you include angular -mocks after angular and use the code this method and you can control both requests and responses, including headers and delays of a fake response, etc.

0
source

For an alternative, more automated backend method, scoffing , check out swagger-api-mock , which goes well with rest-json . Together, these modules can be used to generate $ httpBackend: rest-json.js responses as http-like access to json data and swagger-api-mock / lib / mock-data.js as a generator for jag mock data objects based on swagger (or json schema)

0
source

Source: https://habr.com/ru/post/1479628/


All Articles