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

Implementing external JavaScript files such as Bootstrap and jQuery into a ReactJS application

Just diving into ReactJs, I've got static files like bootstrap.min.js, jquery.min.js, and more in my assets folder. Trying to incorporate them into my ReactJs App but running into issues. Added the code below to my index.html file, however it's ...

Angular 1: selecting all checkboxes within an extensive ng-repeat list

I am encountering a performance issue with a table that includes hundreds of rows, each containing a checkbox. When I use the "Check All" option at the top to select all checkboxes in one go, the browser becomes unresponsive, especially in IE11 which is th ...

IFrame displaying blank page instead of report

The following code snippet displays a report within an IFrame: HTML <div id="dialogReport"> <div> <iframe id="reportFrame" style="width: 800px; height: 600px; border: 2px solid black; margin: 10px auto;"> </iframe> </di ...

Looking to distinguish selected options in a multiple select in AngularJS by making them bold?

When working with Angular, I have a multiple select drop down with options such as Select fruits, Apple, Orange, Banana. How can I make the selected options, like Banana and Apple, appear in bold and change background colors? ...

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...

Message displayed on picture carousel

<div class="slider"> <div> <img src="http://kenwheeler.github.io/slick/img/fonz1.png" /> <p class="projectname">Project</p> <p class="clientname">Client Name</p> </div> &l ...

In order to ensure accuracy, the 'to' date must always be after the '

By default, when selecting a start date, the end date should be displayed as greater than the start date. However, in my current code, if I select the start date, the end date is set to be the same as the start date. Below is my code snippet. Thank you in ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

Having trouble with updating label text in MUIDataTable in ReactJS?

Looking to implement multi-language support in MUI Datatables. I have been able to modify the translations, but when attempting to change languages by providing a different object with new translations (verified using console log), the label texts do not u ...

Error Encountered in jQuery UI SelectMenu

Struggling to integrate the jQuery UI SelectMenu, I keep encountering the same error in the browser console. Below is the HTML Code: <select name="files" id="files"> <optgroup label="Scripts"> <option value="jquery">jQuery.js</ ...

Troubleshooting Yeoman and Angular: Routing troubles persist

I recently started exploring with yeoman to develop angular applications. I am facing an issue while trying to create routes using yo:angular route. After running the command: yo:angular route foo yeoman generates the following files: app/scripts/contr ...

The .keypress() function isn't behaving as expected

I've encountered a coding dilemma. Below is the code in question: $(document).ready(function () { var selectedDay = '#selected_day'; $(function () { $("#date").datepicker({ dateFormat: "DD, d M yy", a ...

Rearranging a JSON Object post editing

Currently, I am working on a project where I need to display and sort a list of items based on a JSON object. This includes sorting by both string values and integers within the object. So far, I have been successful in listing and sorting the items by st ...

Is there a way to verify if the meteor.call function was executed successfully?

In my meteor/react application, I am working with two components. I need to pass a method from one component to the other: saveNewUsername(newUsername) { Meteor.call('setNewUsername', newUsername, (error) => { if(error) { ...

Tips on navigating the scroller vertically as the user interacts with a selected div by scrolling up and down

On my webpage, I have various div elements displayed. Each div has the options to move it up or down using the buttons labeled "UP" and "Down". When a user selects a div, they can then use these buttons to adjust its position. I am looking for a way to au ...

Is there a way to extract a username from LDAP?

Can you help me understand how to dynamically retrieve a username from LDAP? In the code snippet below, I have hardcoded the username as 'smith2': $_SERVER["REMOTE_USER"] = 'smith2'; $param = $_SERVER["REMOTE_USER"] By using this appr ...

The step-by-step guide to automate clicking on an angular dropdown menu using Selenium

Having some trouble using python selenium to automate report generation on a website. The javascript is making it difficult for me to identify the element I need to click on the page. When inspecting the element in Firefox, there is a DOM Event icon that c ...

Implementing dynamic data filtering in Vue.js is a valuable feature that

I'm working on a Vuejs project where I need to filter out only the questions with reviewed:true and get the count of them. However, I'm encountering an error while using the code below: TypeError: question.reviewed.includes is not a function. Can ...

Filtering tables in Angular 6 using checkbox options

I have a functional code snippet that filters a table using checkboxes. However, I am facing an issue when unchecking a checkbox. It does not return the original array as expected. .html <ng-container *ngFor="let group of groups"> <label cla ...

Glitched Water Reflection in THREE.js

Creating a water scene using JavaScript. I followed the official examples to set up the scene, but the reflection seems off after loading an external GLTF model. Initially everything looks fine, but once I start moving the camera, things go awry. I suspe ...