What is the best way to alternate $httpBackend when[method] declarations in unit tests to handle multiple requests?

When conducting my testing, I set up the model data and mock the response:

beforeEach(function(){
   var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
   $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000});
});      

it('should discover 5000 users in channel 12345', function(){
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000);
});

In the subsequent test statement, I need the updated value for the channel as everyone has left. This scenario triggers different behavior, so mocking the second request enables me to test that behavior accurately.

However, trying to add $httpBackend.whenGET in the next it statement does not replace the original mock value from beforeEach. It appears to retain the initial mock value:

it('should find 0 users in channel 12345', function(){
    $httpBackend.whenGET(re).respond({id:12345, usersOnline:0});
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000); //fails
});

If attempted without using beforeEach, both tests fail with the common "unexpectedGet" error message.

it('should find 5000 users in channel 12345', function(){
     var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
     $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000});
    expect( UsersOnlineService.data.usersOnline).toEqual( 50000); //fails
});

it('should find 0 users in channel 12345', function(){
      var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/);
     $httpBackend.whenGET(re).respond({id:12345, usersOnline:0});
    expect( UsersOnlineService.data.usersOnline).toEqual( 0); //fails
});

So, how can we effectively modulate mock data between requests?

I also experimented with:

  • inserting a beforeEach clause between it statements
  • assigning a .respond( to a variable like fakeResponse, and then adjusting the value of fakeResponse in each following it statement.

Answer №1

resetExpectations()

Implementation

afterEach($httpBackend.resetExpectations);

Explanation

When resetExpectations is called, all request expectations are cleared while keeping the backend definitions intact. This function is useful in multi-phase testing scenarios where you need to reuse the same $httpBackend mock instance.

Source: https://docs.angularjs.org/api/ngMock/service/$httpBackend

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

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

Encountering issues when implementing react-router with the client-side library

After following the author's suggestion, I've successfully loaded the client-side library. The recommended method is to simply drop a <script> tag in your page and use the UMD/global build hosted on cdnjs. I have ensured that ReactRouter i ...

AJAX request post parameters not recognized in ColdFusion form scope

I am currently developing a ColdFusion 8 training application that involves creating AJAX requests without using any libraries like jQuery. This is to support a basic CRUD application where data is retrieved and processed through various layers of the syst ...

Tips for ensuring a successful POST request using a hyperlink tag

Within my view file, I have the following code snippet: <a href="/logout" role="button" class="btn btn-lg btn-primary left-button">Logout</a> Inside my app.js file, I have implemented the following route for loggi ...

React page is not loading properly after refreshing, displaying unprocessed data instead

Hello everyone! I am currently working on developing an app using Node, React, and Mongoose without utilizing the CRA command, and I have also incorporated custom webpack setup. Initially, I was able to build everything within a single React page (App.jsx ...

What is the best way to access the watchExpression within the listener of the $watch function?

Is there a way to access the watchExpression inside the listener function? My goal is to extract parameters from the watchExpression. $watch(watchExpression, [listener], [objectEquality]); ...

The function service.foo is not recognized in Angular

My service function is not being recognized by my component import { Injectable } from '@angular/core'; import { ToastController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class LocationService { ...

Show only the lower left quadrant within the img tag during the prepend operation

I'm attempting to add an <img> tag in front of a <div> similar to this example on JSFiddle. However, I have a specific requirement to only display the bottom left quarter of the image instead of the entire one. HTML Markup <div id="my ...

Obtain the parameter of a parent function that runs asynchronously

Here's the code snippet I'm working with: function modify( event, document ) { console.log( "document name", document ); //I need it to be 'file', not 'document'. documents.clients( document, function( clientOfDocument ...

I am encountering errors when running NPM start

After setting up my webpack, I encountered an error in the terminal when attempting to run the code npm start. The specific error message was related to a module not being found. Can someone please assist me with resolving this issue? > <a href="/c ...

Javascript generates a mapping of values contained within an array

In my current project, I am developing a feature that allows users to create customizable email templates with placeholder tags for content. These tags are structured like [FirstName] [LastName]. My goal is to brainstorm the most effective method for crea ...

Exploring nested optgroup functionality in React.js

Within my code, I am utilizing a nested optgroup: <select> <optgroup label="A"> <optgroup label="B"> <option>C</option> <option>D</option> <option>G</option> </optg ...

Guide to retrieving a JSONArray using JavascriptInterface

I attempted to collect form data from an HTML using Javascript and send it back to Java as a JSONArray. However, I am encountering issues with the correct return of the JSONArray in the JavaScriptInterface. The JavaScript functions flawlessly in Chrome, i ...

Is there a way to disable auto rotation on a website when accessed from a mobile phone?

My current solution involves the following code: @media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { html{ -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -ms-transform: rotate(- ...

Utilize Jquery to insert the text into the input or textarea field

<div class="ctrlHolder"> <label for="" id="name.label">Name</label> <input name="name" id="name" type="text" class="textInput small" /> <p class="formHint">Please enter the name of the item you are submitting</p> </di ...

Ways to stop the react-router from causing the page to refresh

Need assistance with React Router issue I'm working on a project in reactJs using react-router-dom v5. I have set up a default route for routing. <Redirect to={"someComponent"}/> The problem is that when I refresh the page, it auto ...

Having trouble showing the material-ui icon on my navigation menu

How can I use Material-UI icons like <AddOutlinedIcon /> in my nav menu without displaying the actual code before the menu name? Do I need to escape the icon code somehow to make it appear correctly? The intended result is to have a + icon displaye ...

Using the codesnippet feature in CKEditor in combination with highlight.js

I am currently experimenting with implementing the highlight.js library in conjunction with the CKEditor addon called CodeSnippet. Although I have successfully integrated the CodeSnippet addon into my CKEditor, the code is not being properly detected, col ...

The error message states: `res.Send function is not recognized as a valid

Recently, I've been working on a function that goes like this: app.get('/counter', function (req, res) { console.log('/counter Request'); var counter = 0; fs.readFile(COUNTER_FILE_NAME, function(err, data) { c ...

Search for text within the nearest <p> tag using HTML and jQuery

My table contains different td elements with the same ID, as shown in this foreach loop: <td class="AMLLeft" style="display:inline-block; !important">ID: <p class="important">${item.id}</p> </td> <td align="right" nowrap="tr ...