Angular's ngMock $httpBackend feature now allows developers to split their mocks into separate files for

I am currently developing a large angular application that requires mocking the entire API within the browser, also known as backend-less development. Each section and view in my application will have its own mock definitions.

I am aware that I can utilize the ngMock module's $httpBackend service to mock AJAX calls, which is exactly what I need. I have come across a functional snippet on jsfiddle.

However, I am struggling with how to organize this into multiple files. With hundreds of pages and potentially numerous RESTful resources, it is not feasible to place everything in one source file. This leads to an architectural question: what is the most effective approach (one that is functional, scalable, and easy to maintain) for dividing thousands of whenGET and whenPOST calls into separate files that can effectively mock the same API? How should these mocks be structured within the project file system? Should each module in the app have its own run() method? Is it possible to load mocks from JSON files?

I would greatly appreciate both an explanation and a demonstration.

To facilitate the response, here is the relevant part of the fiddle:

myApp.run(function ($httpBackend) {
    var phones = [{name: 'phone1'}, {name: 'phone2'}];

    $httpBackend.whenPOST('/phones').respond(function (method, url, data, headers) {
        console.log('Received these data:', method, url, data, headers);
        phones.push(angular.fromJson(data));
        return [200, {}, {}];
    });

    $httpBackend.whenGET('/phones').respond(function (method, url, data) {
        console.log("Getting phones");
        return [200, phones, {}];
    });

    $httpBackend.whenGET(/\.html$/).passThrough();
});

Answer №1

If you need to fetch data using a similar approach, consider the following code snippet:

YYYModule.service('CustomDataProvider', function() {
  this.getData = function(url) {
    var request = new XMLHttpRequest();
    request.open('GET', url, false);
    request.send(null);
    return request.response;
  };
})
.run([
  '$httpBackend',
  'CustomDataProvider',
  function($httpBackend, CustomDataProvider) {
    $httpBackend.whenGET(/i18n/).passThrough();
    $httpBackend.whenGET('/api/yyy/zzz').respond(function(method, url, data) {
      data = CustomDataProvider.getData('yyy/custom.json');
      return [200, data];
    });
  }
]);

To organize your mock data better, consider dividing them into separate folders or modules. This implementation should work smoothly :)

Note: The above code is written in JavaScript, not coffeescript.

Answer №2

I encountered a similar question and managed to find a solution.

It's worth mentioning that I utilized generator-cg-angular, which provided the initial file structure.

index.html ..................... primary HTML file
app.js ......................... setup for Angular module and routes
httpBackendStub.js ............. backend stub module
/service ....................... directory for Angular services
    dimension.js ............... sample service
    dimension-spec.js .......... unit test for the sample service
    dimension-stub.js .......... mock backend with routes and data

The data-concat="false" attributes indicate that all backend stubbing will be taken out during the build process.

index.html

<!-- Bower components and Angular app scripts included here -->
...
<!-- Backend stubbing -->
<script src="bower_components/angular-mocks/angular-mocks.js" data-concat="false"></script>
<script src="httpBackendStub.js"        data-concat="false"></script>
<script src="service/dimension-stub.js" data-concat="false"></script>
...
<!-- Initial HTML markup -->

httpBackendStub.js

angular.module('app')
    .config(function($provide) {
        $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
    })
    .run(function ($httpBackend) {
        // pass templates
        $httpBackend.whenGET(/partial\/.*/).passThrough();
    });

service/dimension-stub.js

angular.module('app').run(function ($httpBackend) {

    $httpBackend.whenGET('api/dimensions').respond([
        {
            name: 'Medium',
            ...
        },
        ...
    ]);

});

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

Creating a seamless connection between a nodejs backend and a frontend interface

I'm facing an issue with my CRUD app developed using nodeJs. The app interacts with a mysql database to perform Create, Insert, Delete, and Read operations. Here's an example of a read operation: app.get('/run',(req,res) => { con ...

What steps should I take to make this slider functional?

How can I achieve a sliding effect on this code? I want the div to slide out when the button is clicked, but I also want the button itself to move. Additionally, how can I ensure that the image and text are displayed in two columns? In my IDE, it appears a ...

Global error handling for URQL GraphQL mutation is a critical aspect that needs to be effectively implemented

Here's the technology stack I'm using: react v17.0.2 graphql v16.8.0 graphql-ws v5.14.0 urql v4.0.5 I rely on Hasura Actions to interact with a REST API and am in need of a solution for handling global errors for all mutations. For instance, I ...

Cover the <img ...> tag in HTML using JavaScript

I'm currently working on creating a simple game involving sliding ice-blocks. I ran into an issue while testing this JSFiddle and I'm looking to "hide" the image/button triggered by the line alert('Game starts!');. I attempted using sta ...

transferring documents using multer

As a novice in JavaScript, I am exploring the use of multer for file uploads. Below is my current code: let express = require('express'); let im = require('imagemagick'); let gm = require("gm").subClass({ imageMagick: true }); let ...

Updating an array using `setState` does not result in the array being updated

I created a component that uses the .map() method to render an array of students and has a button to shuffle and update the display. However, I'm facing an issue where the display does not update every time I click the button. const Home: NextPage = ...

Error returned when making an AngularJS call to a Java Restful Webservice

My current project involves a restful webservice that is responsible for returning a list of users. This webservice is being called using AngularJS framework. Below is the code snippet for my Restful Webservice: package webservice; import java.sql.Connect ...

connecting a JavaScript object literal to a specific address within an HTML document

I'm encountering an issue with creating an object that contains properties such as {"name":"John Doe","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e08e818d85a0848f8d81889c8b848d8a">[email protected]</ ...

What could be the reason for an empty FormData map being fetched when testing a fetch call in React?

Currently experimenting with a fetch call using Formdata in a react app while utilizing jest for testing. export const submitform = async (url:string, file:File, params:{}) => { const body = new FormData() body.append('file', file) if ( ...

Guide on extracting the content of tables from the <td> tags based on the value in the <th> tag

I have a large table in HTML that looks like this: <table id="selectTerminals" size="35"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Full Name</th> ...

Node Signature Generation for Gigya Comment Notifications

I am currently using the Gigya Comment Notification service within my node application and attempting to generate a valid signature. Despite following the documentation, my code is producing an incorrect hash. Below is the code I am using: var crypto = r ...

Connecting AngularJS controllers and services through data binding

I'm having trouble with setting up data binding between my controller and service. The issue seems to be with calling the factory method from other services and seeing the controller attributes update accordingly. I've tried different approaches ...

Employing JQuery Cycle and automatic resizing background images

Is there a way to make jquery's cycle plugin resize images automatically as the user scales the window size? Currently, it cycles through images based on the initial screen size and does not adapt afterwards. Any suggestions? <?xml version="1.0" e ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

Incorporating Error Management in Controller and Service: A Step-by-Step Guide

Take a look at the structure of my angular application outlined below: Within my 'firm.html' page, there is a button that triggers the code snippet provided. Controller The controller initiates a Service function. The use of generationInProgre ...

Having difficulty establishing a connection between my node.js application and the database

I've been struggling to establish a connection between my application and the database. Despite attempting the code below, my models are still not being recognized. const MongoClient = require('mongodb').MongoClient; const assert = require(& ...

Encountering an issue with file uploading in Firebase: Error message indicates that AppCheck is being utilized before activation

I am facing an issue while trying to upload a file to my firebase account. Whenever I attempt this, I encounter the following error message: Uncaught (in promise) FirebaseError: AppCheck: AppCheck is being used before activate() is called for FirebaseApp ...

Is there a way to automatically send users to a different PHP file once they click "submit"?

I need to redirect to a different php file named index2.php. The username and password values are already set as follows: Username=sid, Password=yeaoklogin. When the user clicks on the Login button, they should be redirected to a page called index2.php. ...

Comparing Express.js View Engine to Manual Compilation

Currently, I am utilizing Express.js along with the hbs library to incorporate Handlebars templates in my application. Lately, I've delved into establishing a build system using gulp for my app and stumbled upon packages like gulp-handlebars. My query ...

What is the best way to transfer variables from a JavaScript file to the tailwind.config file?

For my current project, I have decided to implement tailwind css for the first time. I understand how to define variables in tailwind-config for properties like 'colors' and 'border-radius' However, in this particular situation, The v ...