Extracting information from JSON fixture within simulated Angular service

I recently developed a mock Angular service specifically for testing a controller. However, whenever I run my tests, an error pops up saying:

Unexpected request: GET ./fixtures/stats.json
.

This is how the code looks like in mock.players.service.js:

'use strict';

angular.module('mockPlayersService', [])
  .factory('playersService', ['$http', '$q',
    function($http, $q) {
      var playersService = {};

      playersService.stats = $http.get('./fixtures/stats.json');

      playersService.getStats = function() {
        var defer = $q.defer();
        defer.resolve(this.stats);
        return angular.extend({$promise: defer.promise}, this.stats);
      };

      return playersService;
    }]);

I am thinking maybe there's something missing in my controller spec to handle this GET request, or should I include the 'fixtures' path in my 'karma.config.js' 'files' array?

UPDATE: As per my current setup (which is functional), it looks like this:

playersService.stats = {
  'firstName': 'John',
  'middleName': 'James',
  'lastName': 'Doe',
  'city': 'Cleveland',
  'state': 'OH',
};

playersService.getStats = function() {
  var defer = $q.defer();
  defer.resolve(this.stats);
  return angular.extend({$promise: defer.promise}, this.stats);
};

My goal now is to relocate that existing playersService.stats object into a JSON fixture.

Answer №1

If you want to simplify things, consider having karma handle your fixture files. In the karma.conf file, you can insert the following code:

  { pattern:  './fixtures/*.json',
    watched:  true,
    served:   true,
    included: false }

It appears that karma serves files from a base root, so you might need to adjust the URL provided to $http.

I'm not quite sure why there is a need for a MockService alongside your actual service. It seems like an overly complex approach. A more common practice is to utilize your real service and mock the backend. Here's an example of how you can do this in your tests:

before(inject(function( $httpBackend, playersService) {
    o = playersService;
    back = $httpBackend;

  back.whenGET('/therealPath').respond({});


}));

You will still need a method to load your fixture files, but one option is to use karma-read-json and follow a similar pattern like this:

var valid_respond = readJSON('./fixtures/stats.json');
$httpBackend.whenGET('/therealPath').respond(valid_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

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

Interacting with a form input by triggering the onChange event

I am encountering a problem where I need to be able to select a radio button both onChange via keydown and mouse click. However, I am struggling with accessing both event parameters of the on keydown and on mouse click within the same function. As a result ...

How can JavaScript be used to populate a textbox value from a URL parameter?

After a user submits the script below, I want to redirect them back to the same page and fill in the dropdown menu and input box with values from the URL parameters. However, the fields are not populating after the redirect. Additionally, I need to remove ...

How can you transform an array in php to a JSON format?

Here is an array that I would like help converting into JSON format: <?php $txt=array("apple","orange","papaya"); json_encode($txt); ?> The current output is: ["apple","orange","papaya"] However, I am looking to get the output in this for ...

Dividing a string using regex to deal with numerical issues

My task involves processing a list of strings that look like this: Client Potential XSS2Medium Client HTML5 Insecure Storage41Medium Client Potential DOM Open Redirect12Low The goal is to split each string into three parts, like so: ["Client Potential X ...

Unable to Retrieve Data from JSON File

Currently, I'm attempting to retrieve values from a JSON file: { Float : null , test : "hello" , Int : 2 } Unfortunately, the method I'm using below seems to be ineffective and is failing to load the file contents. Despite my efforts, I encoun ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

Angular Redirect Function: An Overview

In the Angular project I'm working on, there is a function that should navigate to the home when executed. Within this function, there is a condition where if true, it should redirect somewhere. if (condition) { location.url('/home') ...

Enabling draggable functionality for divs using JSPlumb and a toggle button

http://jsfiddle.net/taoist/fsmX7/ The scenario presented in the code snippet above involves toggling the draggable state of the .textDivContainer element based on user interaction. The desired behavior is for the element to be non-draggable by default, an ...

Dynamically populate an HTML table/grid in CRM 9 with data retrieved from JavaScript records

Currently, I am developing an HTML Page within Dynamics CRM 9.0 environment. A Webresource JavaScript has been created and linked to the HTML page. There is a specific function in the JavaScript that retrieves data from the CRM entity using the following c ...

Angular - Dividing Values within Input Arrays

In the input field available to users, they can enter multiple inputs separated by commas. <div class="container"> Enter your values:<input type="text" multiple #inputCheck> <input type="submit"(cli ...

AngularJS - Highlighted row value

Here is a helpful example you can refer to: Check out the demo here: The code provided works well, but I would like to add a button. When this button is clicked, an alert should display the value of the name column - for example, "Noodles". This snippet ...

Invoke the bootstrap js collapse() method within an Angular/Typescript environment

Currently, I am utilizing Bootstrap 3 alongside Angular 2 to collapse/hide content. However, I am facing an issue where I need the ability to collapse it when double-clicking on the button. Even though I created a function for this purpose, I seem to be un ...

Uploading and previewing files in Angular

Using the ng-file-upload library, I am able to successfully post files to my backend Web Api. The files are saved in the folder: "~/App_Data/Tmp/FileUploads/" The file path is also stored in my database. When I enter edit mode, I want to display a previ ...

Issues with Ionic Deploy causing app to not update

I am currently working on implementing ionic deploy in my app, but I have encountered some errors. The specific errors I am facing are as follows - Failed to load resource: the server responded with a status of 422 (UNPROCESSABLE ENTITY) ionic.cloud.min. ...

Implementing Firestore Read Limitations in a React Application

I have encountered an issue with Firebase billing based on the number of document reads. There is a daily limit of 50k reads per day in Firestore, but when I try to fetch documents in my React app, it triggers a quota exceeded error. FirebaseError: Request ...

How can I add a character at a precise location while keeping the existing tags intact

Latest Update After further testing, it seems that the code performs well with a faux spacer, but runs into issues with the regex. The following scenarios work correctly: Selecting words above or below the a tag Selecting just one line directly above or ...

Sorting JSON data in EJS based on categories

Hello, I am facing a dilemma. I need to apply category filtering to a JSON file but I am unsure of how to proceed with it. For instance, I wish to filter the 'vida' category along with its description and price. I seem to be stuck at this junctu ...

Using a Firebase forEach loop to push items into an array and returning the completed array

At the moment, I am facing difficulties with nodejs (v6.14.0) because I made a post request that needs to complete some tasks before returning a valid response. The issue is that I receive an empty array as a response initially (the response becomes valid ...

What is the best way to assign a PHP array to an Angular variable?

Currently, I am working on a web development project where PHP is being used to retrieve match information from the database and store it in an array. My goal now is to utilize Angular to display this data. Can you suggest how I can effectively transfer ...