Jasmine: Methods for verifying if the accurate URL is invoked during a GET request

I need to test a service function, but I'm unsure how to mock an internal service function that is called within the main function. My goal is to verify if the correct URL is being accessed.

Below is the code snippet for my service:

angular.module("myModule").service('myService', MyService);

MyService.$inject = ['$http'];

function MyService($http) {
    var myService = this;

myService.request = function (reqType, url, headers, requestBody, fnc, fncFail) {
        $http(createRequest(reqType, point, headers, requestBody)).then(function (response) {
            if (typeof fnc == 'function') {
                fnc(response.data);
            }
        }, function (response) {
            if (typeof fncFail == 'function') {
                fncFail(response);                
            }
        });
    };

myService.getInfo = function (id, fnc, fncFail) {            
        myService.request("GET", "myURL", {"Accept":"application/json"}, null, function (data) {
          fnc(data);
        }, fncFail);
};

Now I have a segment of my testing suite:

beforeEach(inject(function ($injector) {
    service = $injector.get("myService");
    httpBackend = $injector.get("$httpBackend");
    http = $injector.get("$http");      
}));

it("Verifying if getInfo function is calling the right URL", function () {
    spyOn(http, 'get').and.callThrough();
    myService.getInfo(id, fnc, fncFail);
    expect(http.get).toHaveBeenCalledWith("myurl");
    httpBackend.flush();
});

I am uncertain whether this is the most effective way to test my "getInfo" method due to its dependency on another internal function ("request").

Answer №1

Utilize the $httpBackend method to anticipate XHR requests. By incorporating the subsequent afterEach section, the test will produce an error if the call is not executed.

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

it("function getInfo is called with the correct URL", function () {
    httpBackend.expect('GET', "myurl").respond(200, {mocked: "response"});
    myService.getInfo(id, fnc, fncFail);
    httpBackend.flush();
});

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

Removing classes from multiple cached selectors can be achieved by using the .removeClass

Currently working on enhancing some JavaScript/jQuery code by storing selectors in variables when they are used more than once to improve performance, for example: var element = $("#element"); element.hide(); However, I am facing difficulties while tryin ...

Utilizing an AngularJS factory to invoke a function within another function

I am encountering an issue with my AngularJS factory that consists of multiple functions. My goal is to call one of the functions from within another function, as demonstrated in the code snippet below: .factory("AppStart", function($cordovaSQLite) { r ...

Transmit the data.json file to a node.js server using Postman

Hi there, I have a file named data.json saved on my desktop that I want to send to a node.js function. The contents of my data.json file are structured as follows: [{"key":"value"}, {same key value structure for 8000 entries}] This fil ...

converting an array to JSON format results in a string

I'm attempting to perform an ajax call to a PHP file that will create an array, convert it to JSON, and then display the first item in the array using console.log. Currently, I have this code snippet on my homepage: <script> wi ...

Send the content written in summernote to an AJAX request

I'm having trouble with ajax and javascript, so I need to ask for assistance. Within a form, I have an editor (using summernote editor). <div id="summernote">summernote text</div> After that, I use this ajax function to send the form dat ...

A JavaScript function that fetches the color name based on either the RGB value or the Hexadecimal value

Looking for a JavaScript function that can determine the name of a color. Would like the JavaScript function to be structured as shown below: function getColorName(r, g, b) { .... return <color name>; // such as blue, cyan, magenta, etc. } ...

Creating independent Javascript applications and HTML5 canvas games, optimized for V8 or tailored to the specific browser for optimal performance

Instead of solely targeting Chrome users due to browser performance issues, I am exploring alternative options to create an executable version of a canvas game. Is there a way to integrate v8 for non-Chrome users? Perhaps a web "wrapper" similar to Flash&a ...

Troubleshooting Angular directives and the complications of closures

I am facing a problem with this specific directive: @Directive({ selector: '[imgTest]', }) export class ImgTest implements AfterViewInit, OnDestroy { private originalImage: HTMLImageElement; private secondImage: HTMLDivElement; construc ...

Show the checked options retrieved from controller

I am facing an issue with displaying certain checkbox values from the controller. In order to properly save these values, I believe it would be best to declare them in the controller and then use them in the HTML. However, my current code is not successful ...

Displaying a div after a successful form submission using Jquery

I created two popup windows. One is used to ask the user whether they want to submit the form, and if they click 'yes', the form is submitted. The issue I encountered is that the other popup window should be shown after the form is successfully s ...

Retrieve items from a JSON file using Ionic framework's $http.get method

Issue with Console: SyntaxError: Unexpected token { in JSON at position 119 Xcode controller: str="http://www.website.com/user-orders.php?e="+$scope.useremail; $http.get(str) .success(function (response){ $scope.user_orders = response; ses ...

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

Sorting arrays with nested objects in JavaScript

I am facing a challenge with sorting an array of objects in two specific ways: First, I need to sort the objects by alphabetical order using the country name. Then, inside each country, I have to arrange the scores in ascending order. Below you can find ...

Save to a JSON file

Hey there, I'm having some trouble with pushing a temporary value to a JSON file using the command "MyJSON.name.push". It keeps giving me an error saying "Undefined is not an object". I've tried different approaches and using JavaScript arrays wo ...

Using json_encode with chart.js will not produce the desired result

I am attempting to utilize chart.js (newest version) to generate a pie chart. I have constructed an array that I intend to use as the data input for the chart. This is the PHP code snippet: <?php if($os != null) { $tiposOs = array('Orçamento ...

Getting started with Preact.js: Setting up an auto re-run server similar to React.js

Is there a way to set up a development server for Preact similar to how React operates with npm start? Currently, when I use the same command with Preact, it launches a static server and requires manual restart each time I make changes to my project. Here ...

Migrating to Angular Universal for server-side rendering with an external API server

Thank you for taking the time to read my query. I have developed a project using server-side Node.js and client-side Angular 6. The purpose of the app is to provide information on cryptocurrency prices and details. I am now looking to transition my Angu ...

The functionality for transferring ERC20 claim tokens seems to be malfunctioning

I am facing an issue with my contract while trying to execute the claimFreeToken function. Even though the contract does not have enough tokens, the function does not return an error and the token also does not get received. Can anyone point out where I ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

What is the best way to incorporate GLSL shader code from a separate file into the main HTML document?

Exploring the world of writing shaders has been an exciting journey for me. Using THREE.js to create an OpenGL scene and experiment with GLSL shaders has been incredibly helpful. So far, I have been embedding my GLSL code within a script field in the main ...