Unable to execute controller due to service call testing failure

I'm currently working on writing a code to test the service call in my controller. The goal is to unit test a specific function within the controller that makes the service call and retrieves data. While I am using local JSON for testing purposes, the actual service call will be made eventually.

As I delved into unit testing, I learned that I need to create a spy object. However, I encountered an error stating "TypeError: jasmine.CreateSpyObj is not a function." Being new to unit testing, I am struggling to create a spy object and progress further with my testing. Below is my code, requesting assistance to resolve this issue.

Furthermore, once I successfully create the spy object, I am uncertain about the next steps. My aim is to verify if the service call is successful and if I receive a response from the service.

Any help would be greatly appreciated as I have been facing challenges with this for several days now.

Service Code:

//app is the module name
app.factory('appServices', ['$rootScope', '$http', function($rootScope, $http) {
var appServices = {};
appServices.getData = function(){
      return $http.get('scripts/services/data/unitTesting.json'); 
 };

unitTesting.json Code:

{
"name":"unit testing",
"countryCode": "EG",
"countryName": "Egypt",
"region": "Africa"
}

Controller Code:

getData: function(){
        appServices.getData().then(function(response) {
            if (response && response.data) {
                $scope.testVariable= response.data.name;
            }
        });
    },

Unit Test Code:

  describe('myCtrl', function() {
      beforeEach(module('app'));

      var $controller;

      beforeEach(inject(function(_$controller_){
         $controller = _$controller_;
  }));

 describe('service call test', function() {
 var $http,$httpBackend,appServices,
 myService,$q,$rootScope,controller;

 var mockItem = 
       {
       "name":"unit testing",
       "countryCode": "EG",
       "countryName": "Egypt",
       "region": "Africa"
       }
 beforeEach(inject(function(_$http_,_$httpBackend_,appServices,_$q_, 
 _$rootScope_) {
   $http = _$http_;
   $httpBackend = _$httpBackend_; 
   appServices = appServices; 
   $rootScope = _$rootScope_;
   $q =$q_;
   spyOn(appServices, 'getData').and.returnValue($q.when(mockItem));
   controller = $controller('myCtrl', { $scope: $scope });
 }));
  it('Service call test ', function() {
  controller = $controller('myCtrl', { $scope: $rootScope.new() });
  controller.getData();
  expect(appServices.getData).toHaveBeenCalled();
 }); 
 });
 });

ERROR :

 TypeError: jasmine.spyOn is not a function

Answer №1

Utilize the spyOn method:

jasmine.spyOn(appServices, 'getData');

You can then verify calls in your tests like so:

expect(appServices.getData).toHaveBeenCalled();

After reviewing how you have constructed your spec, may I propose some alternative adjustments to assist in successful execution:

var $rootScope,
    controller,
    $q;

beforeEach(inject(function(_$http_,_$httpBackend_,appServices,_$q_, _$rootScope_){
     $http = _$http_;
     $httpBackend = _$httpBackend_; 
     appServices= appServices;
     $rootScope = _$rootScope_;
     $q = _$q_;
     jasmine.spyOn(appServices, 'getData').and.returnValue($q.when(mockItem));
     controller = $controller('myCtrl', { $scope: $scope });
}));
describe('when retrieving data in the controller', function(){
    it('should call upon appServices.getData()', function() {
        controller = $controller('myCtrl', { $scope: $rootScope.new() });
        controller.getData();
        expect(appServices.getData).toHaveBeenCalled();
    }); 
});

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

Troubleshooting Next.js Mobile Freeze Issue: Unresponsive Scroll After Page Transition

Encountered a strange bug while testing my Next.js + Bootstrap demo project on mobile view. When using the burger menu to navigate to a new page on a mobile phone, attempting to scroll down causes it to stick/freeze/hang inexplicably. Despite my efforts to ...

Incorporating a new method into the Object prototype to provide universal access across all modules

I've been delving into Typescript experimentation and I'm attempting to enhance the Object prototype by adding a property that can be accessed by all objects within my modules. Here's what I've developed so far: In a Common.ts file O ...

Retrieving information from an ajax array in PHP

I am currently attempting to retrieve an array of data using AJAX on the PHP side, but I am facing difficulties in accessing the values in PHP. Here is my JavaScript code snippet: console.log(obj); $.ajax({ method: 'POST', url: '/in ...

Understanding Joi validation - setting a field as optional depending on the input received

I have been struggling to integrate the following joi validation. joiSchema = Joi.object().keys({ taskno: Joi.string().alphanum().required().uppercase().trim(), taskstatus: Joi.valid('G', 'C', 'I', 'S'), ...

How extensive is the reach of ELSA-Workflows?

Check out these queries regarding ELSA: 1. Can you explain the variances between ELSA and the .NET workflow engine? 2. How seamless is it to integrate Elsa with both .NET Core and AngularJS technologies? 3. Is it possible for different users to manage a ...

After updating Angular JS from version 1.2.x to 1.4.x, the ngPattern directive is no longer functioning as

Since upgrading the Angular JS library to version 1.4.1, the pattern validation with angular ngPattern seems to be malfunctioning. Check out the code snippet provided below for reference. <form class="form-horizontal" name="someForm" role="form" no ...

Tips for setting a default value in a Multi Select component with reactjs and Material UI

Is it possible to set a default value on a Multiple selection (CHIP) using reactjs and material ui? Despite searching extensively online, I have not been able to find any relevant documentation addressing this issue. import * as React from 'react&apos ...

How about a fading effect for the select box?

I'm currently working on creating a select tag that opens its options slowly with a fade in, fade out effect when the user clicks on "Actions." I've attempted to use jQuery for this feature but haven't had any luck. Here's my code: &l ...

Can the default position of the scrollbar be set to remain at the bottom?

I have a select option tag with a scrollbar to view the contents in the dropdown. I am looking for a way to automatically position the scroll at the bottom when an item is selected from the dropdown. jquery code $('document').ready(func ...

Include cshtml view in an html page by utilizing the ui-router feature of AngularJS

In the past, I have successfully used ui-router to load multiple html pages within a single html page. Now, I am looking to load my cshtml view inside the html page without using an iframe. Unfortunately, I have been unable to find any helpful tutorials ...

What could be causing the error "Cannot read the state property of undefined" to occur in my code?

I am facing an issue with my constructor that suddenly stopped working and I can't seem to figure out why. Upon analyzing the data, it appears that at line 24, everything is being read correctly including props. However, just one line later when tryi ...

Is there a way to dynamically update the TargetControlID of an AutoCompleteExtender using client-side JavaScript?

Typically, I am able to set the TargetControlID on the server side using code similar to this: AutoCompleteExtender ace = new AutoCompleteExtender(); ace.ID = "AutoCompleteExtender1"; ace.TargetControlID = "whatever"; While I understand how t ...

clearing all input fields upon submission in React Native

I need help resolving an error that occurs when I try to clear text input fields on a button press. Instead of clearing the fields, it throws an undefined error because I am trying to set the value as {this.state.inputTextValue} and then clear it using set ...

Guide to dynamically inserting an audio file into a div with jQuery

I am looking to dynamically insert an audio file. Below are the declared tags: <div> <audio id="myaudio"> </audio> </div> Now, I am trying to add the source dynamically. Can anyone help me with how to add it to the div or audi ...

A JavaScript object featuring a predefined value

I have a simple goal that I'm unsure about achieving. My objective is to create an object that will return a specific value if no property is specified. For example: console.log(obj) // Should output "123" console.log(obj.x) // Should output "ABC" ...

Rendering Local HTML with local styling and scripts in React Native Webview

I am having trouble loading a local HTML, CSS, and JS file in my React Native webview. The CSS is not being applied to the HTML. Here is my folder structure: My HTML file, along with CSS, images, and JS file are all placed in the following app folder stru ...

When attempting to invoke the rest function, an error occurs stating that the dataService.init in Angular is not

Learning AngularJS has been my current focus. To practice, I have been working on a Quiz app tutorial. However, I encountered an issue when trying to call the rest function of a factory after injecting it into one of my controllers. The JSON data for this ...

The JQuery-AJAX script in my Django application, intended to show a preset value in a calculated field, is not functioning as expected

Here are a couple of models from my project: class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) ...

Integrate CSS and Javascript Plugins into your Ruby on Rails application

I am utilizing an HTML, CSS, and JS template to design the interface for my Rails application. Within this template, there are several plug-ins that are required in both CSS and JS formats. I have stored these plug-ins within the "/assets/plugins/" directo ...

React JSX is failing to return either an Icon or String value depending on the input provided by the user for the password

I'm currently developing a registration page where I want to display a message saying "Your password must be at least 12 characters long" or show a green checkmark when the user types a password that meets this requirement. However, nothing is being d ...