The error message states, "undefined cannot be used as a function."

For testing purposes, I am running checks on my Service using httpBackend. Specifically, I am focusing on a simple get request that needs to be tested for the response code. However, despite my efforts, I keep encountering this error:

TypeError: undefined is not a function (evaluating '$httpBackend.expectGET('/api/something').response({})') in test/spec/services/requests.js (line 22)
        test/spec/services/requests.js:22:51
        Error: Unsatisfied requests: GET /api/something in /bower_components/angular-mocks/angular-mocks.js (line 1812)
        verifyNoOutstandingExpectation@/bower_components/angular-mocks/angular-mocks.js:1812:74
        /test/spec/services/requests.js:28:48

This is the service setup:

angular.module('requestService', [])
  .factory('Request', ['$http', 'localConfig', 'Query', function($http, localConfig){
return {
      getRequest: function(fromDate, toDate) {
        return $http({
          url: '/api/something',
          method: "GET",
          params: {fromDate: fromDate,
                    toDate: toDate},
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        })
      }
     }
  }]);

This is how the testing process is structured:

describe('Service: Request', function () {
  var reqService, $httpBackend;
  beforeEach(module('webapp'));
  beforeEach(module('requestService'));
  beforeEach(inject(function(Request, _$httpBackend_){
    reqService = Request;
    $httpBackend = _$httpBackend_;
  }));

  it('should test the response to be 200', function(){
    $httpBackend.expectGET('/api/something').response({});
    $httpBackend.flush();
  });

  afterEach(function(){
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  })
});

EDIT

Following recommendations, changes were made to the test:

it('should test the response to be 200', function(){
    console.log('service: ' + reqService);
    reqService.getRequest('2016-03-26', '2016-03-29');
    $httpBackend.expectGET('/api/something').respond({});
    $httpBackend.flush();
  });

Unfortunately, a new issue has arisen:

 Error: Unexpected request: GET /api/something?fromDate=2016-03-26&toDate=2016-03-29
        Expected GET /api/something in /bower_components/angular-mocks/angular-mocks.js (line 1403)
        $httpBackend@/bower_components/angular-mocks/angular-mocks.js:1403:90
        sendReq@/bower_components/angular/angular.js:11235:21
        serverRequest@/bower_components/angular/angular.js:10945:23
        processQueue@/bower_components/angular/angular.js:15552:30
        /bower_components/angular/angular.js:15568:39
        $eval@/bower_components/angular/angular.js:16820:28
        $digest@/bower_components/angular/angular.js:16636:36
        flush@/bower_components/angular-mocks/angular-mocks.js:1778:45
        /test/spec/services/requests.js:24:23
        Error: [$rootScope:inprog] $digest already in progress
        http://errors.angularjs.org/1.5.0/$rootScope/inprog?p0=%24digest in bower_components/angular/angular.js (line 17178)
        beginPhase@/bower_components/angular/angular.js:17178:88
        $digest@//bower_components/angular/angular.js:16616:19
        verifyNoOutstandingExpectation@/bower_components/angular-mocks/angular-mocks.js:1810:45
        /test/spec/services/requests.js:29:48

Answer №1

You forgot to invoke the getRequest function in the service, which means the ajax call was never made. This is why the expectGET condition was not satisfied and resulted in an Error: Unsatisfied requests:. Additionally, there is a typo where response should be corrected to respond.

it('should verify that the response is 200', function(){
    //performing the action
    reqService.getRequest();

    $httpBackend.expectGET('/api/something').respond({});
    $httpBackend.flush();
});

Answer №2

It appears that the correct method to use is respond() instead of response():

$httpBackend.expectGET('/api/something').respond({});

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

What's the reason my JavaScript isn't functioning properly?

Brand new to coding and I'm delving into the world of Javascript for the first time. In my code, there's a checkbox nestled within an HTML table (as shown below). <td><input type="checkbox" id="check1"/> <label th:text="${item.co ...

Implementing custom click event for selecting checkboxes in Material-UI table rows

I have been working with the material-ui data table to implement sorting functionality. One feature I am trying to add is a checkbox on each row. The challenge I am facing is that when clicking on the checkbox, it also triggers the row link, which is not t ...

Issue with accessing Factory in Controller Method in AngularJS

When I invoke a factory method within the controller, everything works smoothly. However, when I call a factory method within a specific controller method, it returns as undefined. Below is my factory setup: app.factory('config', ['$http&a ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

React is throwing a parsing error due to the incorrect use of braces. Remember, JSX elements must be wrapped in an enclosing tag. If you were trying to include multiple elements without a parent tag, you can use a JSX fragment

Having recently started working with React, I came across this code snippet return ( <div> dropdown ? (<li className='goal-list-item' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>) : ...

Setting up server-side CORS in ExpressJS will not include the "Access-Control-Allow-Origin" header

Looking to tackle a CORS request for an ExpressJS server, which is new territory for me. Despite encountering similar issues in the past, I can't seem to pinpoint the problem this time around. It appears that the required headers may not be in the cor ...

Limitations exist when trying to open multiple tabs using the same link in Express puppeteer

Update: I found that changing "networkidle0" to "networkidle2" fixed the issue. Special thanks to vsemozhebuty for their helpful comment on this topic. I'm currently working on a web scraping project using Express and puppeteer. The following code sn ...

Vue/Vite vanilla setup encountering a 'Failed to fetch dynamically imported module' TypeError

We're currently working with a vanilla Vue/Vite setup and I'm encountering the error message TypeError: Failed to fetch dynamically imported module in Sentry logs. It appears that these errors coincide with new deployments to production, but I d ...

Is there a way to showcase an array parameter in a url's format?

Objective Currently, I am developing a project using NextJS 12 and I am facing an issue with passing an array as a parameter to the query. Desired Outcome The expected format for passing the array as a parameter should look like this: /path?address_id=1 ...

Exploring methods to reload a parent window from a child window using PHP

After opening a popup window from a modal, I am now trying to refresh the page where my modal is located. I have attempted to write some code that I found here, but it doesn't seem to be working. Here is an example of what I have tried: // This fun ...

Tips for concealing an alert using an 'if' statement

There is an alert that pops up on a website only on specific days of the year. My query is: How can I make the alert hidden if the date is not one of those special days? I attempted the code below, but it seems to just delay the alert based on certain con ...

The functionality for navigating the Angular uib-dropdown using the keyboard is currently experiencing issues

I am currently utilizing Angular Bootstrap 2.2.0 in conjunction with Angular 1.5. Despite enabling the keyboard-nav option, I am experiencing issues with keyboard navigation on UIB dropdowns. Below is the snippet of my code: <div class="btn-group" ...

Executing test units in Angular

While setting up unit tests for my Angular app, I expect the ngInit function to be called. Component.ts: ngOnInit() { this.topToolBarService.change.subscribe(customer => { this.filter.customerid = customer; this.customerid = customer; ...

Using the fieldset element in AngularJS Material causes disruptions in my flex layout

My current issue can be illustrated through two code examples: The first example functions properly when the fieldset is not included. In the second example, including the fieldset causes the layout to extend beyond the window when there is long text (in ...

What exactly is the functionality of the jQuery.on() method?

I am curious about the functionality of this function and how it operates. Does it follow these steps: Identify element(s) using their selectors Assign event-handlers to them Execute a setInterval on that selector, consistently delegating and then undeleg ...

Testing a class that includes a static method with Mockito: a step-by-step guide

import com.ssctech.eventmsg.app.model.EstimatedCash; import com.ssctech.eventmsg.app.properties.KongAPIProperties; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory. ...

AngularJS: How can I eliminate the #! from a URL?

Looking for guidance on how to remove #! from the URL in AngularJS using ng-route. Can anyone provide a step-by-step process on removing #!? Below is the code snippet: index.html <head> <script src="https://ajax.googleapis.com/ajax/libs/ang ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...

Exploring MessageEmbed Properties

I am trying to retrieve the description of this Message embed. So far, I have used console.log(reaction.message.embeds) which displays the information below. However, when I attempt to access the description directly with console.log(reaction.message.embe ...

Issues with posting form data in AngularJS are occurring

Here is the code I am currently using: On the Angular side vm.onSubmit = function(){ var person = vm.formData.slice(0, 1)[0]; //This line extracts the required fields from the model object which is nested in an array. $http({ ...