Angular Unit Testing: Executing Multiple expectGET's within a Singular Test

I am facing an issue with a unit test that fails to read the JSON in the second request properly

This is my implementation of the Config factory

(function() {
    'use strict';

    angular.module('commercial.factories').factory('config', config);

    function config($http) {

        var service = {
            GetConfig: getConfig
        };

        return service;

        function getConfig(identifier) {
            var _config = {};

            // Checking for URL match in mapping json file
            var urlMap = $http.get('./app/core/urlMap.json').then(function(response) {
                for (var i = 0; i < response.data.length; i++) {
                    if (identifier.toString().toLowerCase().indexOf(response.data[i].url.toLowerCase()) > -1 || response.data[i].clientId === identifier) {
                        return response.data[i].contentFolder;
                    }
                }
            });

            // Fetching the config for the related client found in the URL map (above)
            return urlMap.then(function(response) {

                var contentFolder = response;
                return $http.get('./content/' + response + '/config.json')

                .then(function(response) {

                    if (Object.keys(_config).length === 0) {
                        _config = response.data;
                        _config.contentFolder = contentFolder;
                    }

                    return _config;
                });
            });
        }
    }
})();

And here is my test setup...

describe('Config Factory', function() {

    var configFactory;

    beforeEach(inject(function(_config_) {
        configFactory = _config_;
    }));

    describe('GetConfig()', function() {

        it('should fetch the urlMap from the urlMap.json', function() {

            var identifier = '_default';
            var mockData = [{ url: identifier, contentFolder: '_default' }];

            $httpBackend.expectGET('./content/' + identifier + '/config.json');
            $httpBackend.expectGET('./app/core/urlMap.json').respond(mockData);

            var promise = configFactory.GetConfig(identifier);

            $httpBackend.flush(0);

            promise.then(function(result) {
                expect(result).toEqual(mockData);
            })

        });
    });

Here is the content of the config.json being read...

{
   "clientId":34
}

When running the test, I encounter an error message from Karma stating ...

uncaught SyntaxError: Unexpected token : on line 2 of my JSON.

I suspect that the error may be due to having two expectGET's in the same test case, but I need to investigate further to confirm.

https://i.sstatic.net/VYO83.png

Answer №1

If you encounter issues with single quotes in your mockData array, consider using JSON.stringify(mockData) before responding to the get request. The JSON parser may struggle with this format.

Another observation is a missing period in your expectation:

expect(result) toEqual(mockData);

It should actually be:

expect(result).toEqual(mockData);

Answer №2

Oops, I made a small error in my code.

I realized that I forgot to include a response to the config.json call. Take a look at the corrected code snippet below.

it('should retrieve the urlMap from the urlMap.json file', function() {

        var identifier = '_default';
        var mockData = [{ url: identifier, contentFolder: '_default' }];
        var mockConfig = { clientId: 34 };
        $httpBackend.expectGET('./app/core/urlMap.json').respond(mockData);
        $httpBackend.expectGET('./content/' + identifier + '/config.json').respond(mockConfig);

        var promise = configFactory.GetConfig(identifier);

        $httpBackend.flush();

        promise.then(function(result) {
            expect(result).toEqual(mockData);
        })

    });

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

Avoid choosing the menuItem when clicking on the icon within the Material UI select component

I am trying to create a dropdown menu that allows users to delete items. However, when I click on the delete icon within a menu item, the entire menu item gets selected automatically. How can I prevent this default behavior? Here is my code: { dropd ...

What is the reason for the Client Height value not affecting other elements?

I'm trying to set the spacing of my sidebar from the top equal to the height of the header. However, when I use clientHeight in JavaScript to get the height and then try to apply it to other elements using marginTop or top values (with position includ ...

The words spill across the navigation bar

I am facing an issue with my navbar where the text overflows and creates extra space due to a white background. I have tried resolving this for a while but haven't been successful. I need help from someone knowledgeable in this area. Here are some im ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...

Using karma for angular to compile directives

I encountered a perplexing issue and now I'm feeling stuck. My main goal is to conduct tests on a list of directives within my project. These Directives have the following structure: angular.module('lessons', []).directive('uwTextare ...

Error message: "Window object not defined during NextJS build process."

Why am I encountering a 'window not defined' error? I haven't referenced window or document in my code, and it runs without issues during development but throws an error during the build process. ReferenceError: window is not defined at ...

Utilizing the map() function to parse a Json object

Looking for guidance with working with a JSON object structured like this: {"Title":"asb","Date":"2019","Other":"not important"} How can I correctly read this object and render it in <ul><li> format? Please Note: I have attempted to assign th ...

Tips for effectively utilizing foreach loops in JQuery

I've encountered an issue while displaying a list of data in a table using Smarty templates and foreach loops. I'm trying to make each line clickable to show new data below it, but currently, this functionality only works for the first line. Is t ...

Running shell commands through child_process in JavaScript

Is there a way to execute shell commands from the browser and display the result on the UI using child_process? I'm having trouble fetching the results from the command line asynchronously. Is there something I'm overlooking here? const exec = ...

In mvc.net 4, Ajax is only compatible with the httpGet method and not with httpPost

There are two methods, httpGet and httpPost, inside the Login action. Currently, when an ajax call is made, it only works with the httpGet method of Login. I would like it to work with the httpPost method of Login. Thank you in advance for your answer! ...

techniques for accessing HTML source code through an AJAX call

I am trying to retrieve the HTML source of a specific URL using an AJAX call, Here is what I have so far: url: "http://google.com", type: "GET", dataType: "jsonp", context: document.doctype }).done(function ...

Issue with Ajax post redirection back to original page

I'm facing an issue with my ajax call where I send multiple checkbox values to a php file for processing and updating the database. The post request and database updates are successful, but the page doesn't return to the calling php file automati ...

Node.js: App crashed, standing by for file changes to initiate restart

While I was in the middle of a nodejs course on Udemy, I encountered an issue where the code suddenly started breaking and throwing errors. Even after attempting to replicate the instructor's code, the problem persisted. I sought guidance from this a ...

The jQuery each function in combination with the index function allows for

I'm struggling to make this jQuery script work properly: $(document).on('knack-scene-render.scene_126', function() { $('#view_498 > div.kn-list-content.columns.is-multiline').each(function(index) { if ($(this).eq(inde ...

What is the process of combining a JSON bundle with a Jade template?

As a newcomer to this workflow, I have an Express app set up with Jade as the template engine. My current challenge involves using "gulp-bundle-assets" to bundle all scripts into one file with a hashed name for caching purposes. Additionally, it generates ...

Generate a vector3 with a defined direction

I have a challenge at hand where I am looking to create a 2D flow field in three.js based on a working example I found in p5.js. The original source code for reference is as follows: var inc = 0.1; //Increment of noise var yoff = 0; var scl = var; //Scale ...

Downloading a zip file using PHP works successfully when initiated directly, but encounters errors when attempted through a web application

I have been working on a PHP script that generates a zip file and allows it to be downloaded from the browser. The download function in the code snippet below: download.php // ensure client receives download if (headers_sent()) { echo 'HTTP head ...

Press the button to update several span elements

Imagine I have multiple span elements like this: <span>A</span> <span>B</span> <span>C</span> <span>D</span> and a div element (which will be converted to a button later) named "change". <div id="chan ...

Converting YAML to JSON using Groovy

I'm in need of assistance with converting a yaml file to JSON format within a Jenkins pipeline that is scripted in Groovy. The goal is to parse the YAML content in its JSON format. Within the Groovy script, I have defined a variable called 'data ...

Top strategy for handling $http tasks by dividing responsibilities between a controller and service

(currently using Angular 1.5) After reading various articles - some recent, others outdated - regarding $http requests, promises, and separation of concerns, I have been experimenting with the code example below (Plunker here). I would appreciate feedbac ...