Replicate the functionality of a backend API using AngularJS

Currently, I am in the midst of creating a GUI for an application that is still undergoing API development. Although I have a vision of how it will look, it lacks functionality as of now. Hence, I need to replicate its behavior until the API is fully functional.

To achieve this, I am exploring the usage of $httpBackend. My setup involves using Yeoman.


Installation Attempt

My Angular version is v1.2.6.

The documentation presents three methods for installation:

  • Google CDN at
    //ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-mocke2e.js
  • Bower via
    bower install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25444b425049445708484a464e401740657d0b7c0b7f">[email protected]</a>
  • code.angularjs.org:
    //code.angularjs.org/X.Y.Z/angular-mocke2e.js

Where X.Y.Z represents my specific version number.

Unfortunately, none of these approaches seem to work. Google results in a 404 error and does not allow directory traversal. Bower indicates no available package, with a 404 on code.angularjs.org. Upon further investigation on code.angularjs.org, I discovered that for version 1.2.6, there is a lack of angular-mock availability

However, I did manage to locate a file at

https://code.angularjs.org/1.2.6/angular-mocks.js
, which appears to contain the definition for $httpBackendProvider.

Upon returning to my Yeoman installation, it seems that angular-mocks.js was already installed.

Thus, my first query arises: Is this the appropriate resource to utilize $httpBackend?


Utilization Attempt

Subsequently, I attempted to integrate it into my project:

// Manually running the app to check cookies
app.run(['$cookies', '$location', '$rootScope', '$httpBackend', function($cookies, $location, $rootScope, $httpBackend){

    // Some stuff....

    console.log($httpBackend);

}]);

Regrettably, my app failed to launch, displaying the following error:

Although the app does reveal the contents of $httpBackend, I pondered if relocating it to a different module might be necessary.

Hence, my second question emerges: Is it common for my app to fail loading when incorporating $httpBackend within the app.run() call?

Furthermore, question 3 arises: During testing, should I segregate my $httpBackend functions into a separate module?

Lastly, I contemplate whether this methodology constitutes the most effective approach for API testing.

Answer №1

  1. If you want to simulate your services, try using $httpBackend in this manner:

    $httpBackend.whenGET(/\/api\/foo\/bar/).respond({some:'thing'});

  2. The reason your app is not loading could be due to unexpected requests for partials. To prevent this, consider implementing the following:

    $httpBackend.whenGET(/^views\/.*/).passThrough();

  3. It may be beneficial to separate these into distinct modules so they can be excluded before deployment.

  4. Whether this is the optimal solution depends on your specific requirements. One suggestion is to incorporate various build tools (such as Grunt, Express, Protractor, etc.) that come with a local node server for testing purposes. This way, you can utilize real services for testing, as recommended by @Ronald91.

Answer №2

Currently facing a similar challenge with a project I'm involved in. While we haven't used httpbackend for this purpose, we decided to mock out the backend services using MongoDB. In our app.js file, we configured the routing like this:

  app.get( '/ui/orders/:orderId/details', function( req, res ){
        mongoclient.connect( mongoUrl, function(err, db){
            if( err ) throw err;
            var collection = db.collection('order-details');
            console.log( req.query);
            collection.findOne( { orderId : req.params.orderId}, function(err, docs){
                if( err ) throw err;
                console.log( "Docs...");
                console.log( docs );
                db.close();
                res.send( docs );

            } );

        });


    });

To make use of this routing, we implemented the following service call:

ourApp.factory('orderDetails', function($resource, $routeParams) {
    return function(){
        return $resource('/ui/orders/:orderId/:subSystem', {orderId: $routeParams.orderId});
    };
});

Answer №3

Here is a solution for the "Attempt To Install" issue.

If you're looking to mock data, angular-mocks.js is the way to go. It contains various modules that are handy for mocking, although you don't need to use all of them.

Specifically, for the scenario you described (which I am also trying to address), follow these steps:

  1. Include the angular-mocks.js file in your project.
  2. Add the following dependency to your main app module in order to mock back-end requests:

    var yourApp = angular.module('app', ['ngMockE2E']);

You can utilize the mocks module both in unit tests and during application development.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for recognizing when Vuetify's v-autocomplete has reached the final scrolled item

I am working with a Vuetify v-autocomplete component and I need to implement a feature where I can detect when the user reaches the last item while scrolling, in order to load more items without the user having to manually type for search: // component.vue ...

What steps should I take to resolve the npm UNMET PEER DEPENDENCY notification?

I'm currently using Windows 10 with Node version 5.6.0 and npm version 3.6.0. My goal is to add angular-material and mdi to my project directory. When I run npm install angular-material mdi, I encounter the following errors: +-- <a href="/cdn-cgi/ ...

Introducing a new feature in React-Select: enabling copy-paste functionality for the multi-select text

Incorporating a react-select component (specifically generated using CreatableSelect) into my project has been quite beneficial. This multi select text input feature allows users to conveniently add keywords as options. While the current functionality is ...

Sending empty parameter data via Ajax to an MVC controller

Initially, I had no issues passing a single parameter to my MVC Controller through Ajax. However, when I attempted to add an extra parameter, both parameters stopped sending data to the Controller. Can anyone help with this issue? Thank you! Ajax Code: ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

Retrieving data from MySQL using PHP and AJAX with radio button selection

How can I update my code to display data from the database when a radio button is clicked instead of using a drop-down box? Here is an example of my current radio button code: <Input type='Radio' Name='compcase' value='1'/& ...

Best practice for finding the parent element using Protractor

The recently released Guidelines advise against using the by.xpath() locators. I am making an effort to adhere to this suggestion, but I'm having difficulty locating a parent element. We are currently utilizing the .. XPath expression to access the p ...

Struggling with Responsiveness: Challenges with Detailed Information and Image Grid Design

Encountering challenges in achieving the desired responsiveness for a grid layout consisting of details and an image. The layout displays correctly on desktop screens, with details on the left and the image on the right. However, on mobile screens, the ima ...

Using a Bootstrap modal with angular-ui causes the scrollbar to mysteriously disappear

When I open a modal in my directive code, I use the following method: var modalInstance = $modal.open({ templateUrl: "app/templates/modal-assign.html", controller: "assignModalController", resolve: { "call": function() { ...

initiating a function on a separate webpage using ajax

Our website includes an IIFE script from a third party to check for a specific URL parameter and set a cookie. However, on another page, we need to set this parameter without redirecting the user, reloading the page, or altering the third-party code. The ...

Vanilla JavaScript error: Unable to access property

I am working on implementing a header with a logo and navigation that includes a menu toggle link for smaller viewports. My goal is to achieve this using Vanilla JS instead of jQuery. However, when I click on the menu toggle link, I encounter the followin ...

Unable to locate the reference to 'Handlebars' in the code

I am currently attempting to implement handlebars in Typescript, but I encountered an error. /// <reference path="../../../jquery.d.ts" /> /// <reference path="../../../require.d.ts" /> My issue lies in referencing the handlebars definition f ...

Image uploading in Angular is not compatible with Internet Explorer, however, it functions correctly in Google Chrome

As of now, my implementation has been successful in all browsers except for Internet Explorer 11. Despite being able to successfully upload .jpeg, .jpg, and .png images in Google Chrome, I am facing issues when trying to upload them in IE 11. The code wo ...

highcharts-ng expands in flexbox without contracting

I've encountered an issue while trying to incorporate a highchart within a flexbox container. The chart expands along with the container without any problems, but it fails to contract when the container size decreases. My current setup involves angul ...

Exploring the method of retrieving nested JSON objects in Angular

When my API sends back a JSON response, my Angular application is able to capture it using an Interface. The structure of the JSON response appears as follows: { "release_date":"2012-03-14", "genre_relation": ...

How to use the filter() method to filter an array of objects based on a nested array within each object

The following data presents a list of products along with their inventory information: const data = [ { id: 1, title: "Product Red", inventoryItem: { inventoryLevels: { edges: [{ node: { location: { name: "Warehou ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

Transitioning Angularjs tooltips to Angular 14

I am in the process of transitioning my Web application from AngularJS 1.5.3 to Angular 14.2. One feature used in my application is a popover template, as shown below: html <a id="{{mapObj.stId}}" popover-template="'{{mapObj.statusT ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...