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

Exploring client-server relationships within the Express framework

Is there a way to transfer an object to JavaScript on the client side? I previously asked this question and received an answer, but because I was unable to check it on my computer, I accepted the response. You can view the details here: Client receive jso ...

Attempting to start and restart an asynchronous function using setIntervalAsync results in a TypeError because undefined or null cannot be converted to an

Recently, I've been working on creating a web scraper that utilizes data extracted from MongoDB to generate an array of URLs for periodic scraping using puppeteer. My goal is to make the scraper function run periodically with the help of setIntervalAs ...

Struggling to implement SOAP web service in AngularJS

I'm working on consuming a webservice using the Get method in AngularJS. In my controller, I've used $http to write the code. However, I'm not receiving any response and I'm unsure if the URL is being hit or not. Any corrections or su ...

Problem encountered while trying to publish a post using Iron Router

I'm encountering some difficulties when trying to create a route that allows me to respond to comments (.../comments/:_id/reply) and publish the related post. Below is the code snippet: Publications Meteor.publish('commentUser', function(c ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

In jQuery, conditionally nest divs within another div based on a specific requirement

There is a container with multiple nested elements that need to be rearranged based on the value of their custom attribute. The goal is to reorder those elements at the end of the container if their 'data-keep-down' attribute is set to true, usin ...

Managing State Changes with Redux

Reducers in Redux are primarily designed to be pure functions that take the previous state and an action as arguments, and return a new state object without mutating the previous state. However, it is still possible for developers to directly mutate the st ...

Adjust the class of the iframe element when clicked

I am attempting to change the class of an iframe (soundcloud embedded track) when it is clicked, in order to apply different properties. However, my code doesn't seem to be working as expected. Here is what I have: Here is a snippet from my index.htm ...

Suggestions for improving the smoothness of the Bootstrap toggle hide/show feature

Recently completed my bootstrap toggle hide/show feature and everything seems to be functioning correctly, except for the transition between the different contents. The borders appear jagged and not smooth when activating the toggle. I suspect there may b ...

Angular's $watch function does not receive the parameter 'newVal'

I have been facing an issue displaying messages from a backend response in an Angular AJAX call. I am using a ShareDataService to share data between different controllers. 'use strict'; var angularApp = angular.module('angularApp'); ...

When attempting to run the npm install mathjs command, an error is displayed

Trying to install mathjs using npm but encountering an error: npm install mathjs The error message received is as follows: npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write npm WARN tar TAR_ENTRY_ERROR UNKNOWN: unknown error, write npm WARN tar T ...

Attempting to navigate through nested data within existing mapped data

The data set 1 consists of an array that contains another array called data set 2. Currently, data set 1 is being mapped to display a single-column table with data1.name inside it. The data1.name serves as a clickable button that reveals the related data i ...

How can getters in vuex be utilized uniquely?

After dedicating two weeks to studying Vuex, I find myself pondering the true significance and purpose of getters in the framework. I ran the following code snippet and everything seems to be functioning properly. this.$store.getters["app/url"] ...

The PHP table fails to show up on the screen

I've implemented a PHP script that connects to a MySQL database and is supposed to generate an HTML table. To achieve real-time updates, I've set up a long-polling AJAX script that polls the PHP script every second. Although everything seems to b ...

A Greasemonkey script for organizing and categorizing webpage elements

I've been working on a script to enhance the functionality of Facebook's find friends page by organizing suggested friends based on mutual connections. If you're interested in checking out the code, you can find it right here: http://pasteb ...

Adjusting the background color of the list item

I'm looking for a way to change the background color of the li tag when the user focuses on the input, similar to what can be seen at the bottom of this page here. After researching similar questions, it appears that achieving this effect in pure CSS ...

Is it possible for node-java to accept anonymous functions as parameters in Java?

I am looking to pass an anonymous function from JavaScript to Java using node-java (https://github.com/joeferner/node-java). Below is a snippet of the Java code for reference: public class Example { public Example() { } public interface Callb ...

Tips for validating a text input field depending on the selected value in a dropdown menu using AngularJS

When a user selects from the dropdown menu, they can choose between Number and Decimalnumber. If the user selects Number, the text box should only allow whole numbers (e.g. 22, 33, 444, 345436). The user should not be able to enter decimal values like 22 ...

What is the best way to adjust the size of a Div slideshow using

I need help with creating a slideshow that covers my webpage width 100% and height 500px. The image resolution is 1200*575. Can someone assist me with this? CSS #slide{ width : 100%; height: 500px; } HTML <!DOCTYPE html> <html> ...

The side menu in Bootstrap dropdown experiences a one-time functionality

When navigating through a responsive top menu with Bootstrap, everything works seamlessly - from toggling the menu to dropdown functionality. However, I encountered an issue with the side menu as nav-pills used to select tab-panes. <div class="containe ...