What methods can we use to test angular controller functions that are not within the scope?

In our Angular Controller, there are a few methods that are not on the scope variable.

Is there a way to call or execute those methods inside Jasmine tests?

Here is the main code snippet:

var testController = TestModule.controller('testController', function($scope, testService)
{

function handleSuccessOfAPI(data) {
    if (angular.isObject(data))
    {
       $scope.testData = data;
    }
}

function handleFailureOfAPI(status) {
    console.log("handleFailureOfAPI executed :: status :: "+status);
}

 // controller initialize function
 function init() {
    $scope.testData = null; 

    // partial URL
    $scope.strPartialTestURL = "partials/testView.html;

    // send test http request 
    testService.getTestDataFromServer('testURI', handleSuccessOfAPI, handleFailureOfAPI);
}

 init();
}

Now in my jasmine test, we are passing "handleSuccessOfAPI" and "handleFailureOfAPI" method, but they are undefined.

Below is the Jasmine test code:

describe('Unit Test :: Test Controller', function() {
var scope;
var testController;

var httpBackend;
var testService;


beforeEach( function() {
    module('test-angular-angular');

    inject(function($httpBackend, _testService_, $controller, $rootScope) {

        httpBackend = $httpBackend;
        testService= _testService_;

        scope = $rootScope.$new();
        testController= $controller('testController', { $scope: scope, testService: testService});
            });
});

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

it('Test controller data', function (){ 
    var URL = 'test server url';

    // set up some data for the http call to return and test later.
    var returnData = { excited: true };

    // create expectation
    httpBackend.expectGET(URL ).respond(200, returnData);

    // make the call.
    testService.getTestDataFromServer(URL , handleSuccessOfAPI, handleFailureOfAPI);

    $scope.$apply(function() {
        $scope.runTest();
    });

    // flush the backend to "execute" the request to do the expectedGET assertion.
    httpBackend.flush();

    // check the result. 
    // (after Angular 1.2.5: be sure to use `toEqual` and not `toBe`
    // as the object will be a copy and not the same instance.)
    expect(scope.testData ).not.toBe(null);
});
});

Answer №1

Although this may be an older case, I wanted to share the solution that has been working for me:

Utilize the 'this' keyword in your controller

.controller('newController',['$scope',function($scope){
    var $this = this;
    $this.testMe = function(val){
        $scope.myVal = parseInt(val)+1;
    }
}]);

Test out the functionality with the following code snippet:

describe('newDir', function(){
var svc, 
    $rootScope,
    $scope,
    $controller,
    ctrl;


 beforeEach(function () {
    module('myMod');
 });

 beforeEach(function () {
    inject(function ( _$controller_,_$rootScope_) {

        $controller = _$controller_;
        $rootScope = _$rootScope_;
        $compile = _$compile_;
        $scope = $rootScope.$new();
        ctrl = $controller('newController', {'$rootScope': $rootScope, '$scope': $scope });
    });
});

it('testMe inc number', function() {

    ctrl.testMe(10)
    expect($scope.myVal).toEqual(11);
});

});

Check out the complete code example here

Answer №2

If you don't define those functions in another way, they will not be accessible. When you create a named JavaScript function, it's similar to declaring

var handleSuccessOfAPI = function(){};

This means that the variable is only visible within the block where it is defined and cannot be referenced externally from the surrounding controller.

Any function that can be called separately (and therefore tested) will be present on the $scope of the controller.

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

Trouble with the drop-down menu displaying "string:2" in an AngularJS application

Currently, I am utilizing AngularJS ng-model to choose the value from a drop-down menu. Additionally, I am implementing datatable for organizing the columns. <select id="{{user.id}}" ng-model="user.commit" name="options" ng-change="update_commit_level ...

Angular Script Linking

Hello there! I am currently attempting to add an HTML tag to my response message, but for some reason it isn't working as expected. Here is a snippet of my controller code (in case the API indicates that the account doesn't exist - see this scr ...

Utilizing the Yelp API and/or the Google Places API for project development

Hey there! So I've been given a project for school that involves using either the Google Places API or Yelp API to allow users to search for local restaurants or bars near a specific location. I've spent the last couple of days researching how t ...

Using ng-bind-html does not offer protection against cross-site scripting vulnerabilities

I utilized ng-bind-html to safeguard against cross site scripting vulnerabilities. I came across information about sanitization and engaged in a discussion at one forum as well as another informative discussion. However, I encountered an issue where it di ...

Storing the data retrieved from an HTTP GET request in Ionic 2

I've been working on developing an app and have successfully set up an event provider. Utilizing the Eventbrite API, I am able to retrieve a list of events taking place in a specific city. However, I'm facing challenges when attempting to execute ...

Encountering a missing value within an array

Within my default JSON file, I have the following structure: { "_name":"__tableframe__top", "_use-attribute-sets":"common.border__top", "__prefix":"xsl" } My goal is to add values by creating an array, but I am encountering an issue where my ...

Getting started with ASP.NET vNext 1.0.0-rc1-update1 live stream!

We began working on the project in beta 7 and successfully implemented most of the functionality in version 1.0.0-rc1-update1. Our primary authentication method is MVC and we use web API to provide data. The majority of the functionality resides in client- ...

Verification of three-dimensional password format with the use of AngularJS

I am trying to implement password validation in Angular.js that requires a combination of alphabetical, numerical, one upper case letter, one special character, no spaces, and a minimum length of 8 characters. How can I achieve this using Angular.js? Here ...

ng-pattern mistakenly permits whitespace while regex rules dictate that it should not

ng-pattern is somehow allowing spaces in the specified pattern and I'm puzzled as to why. ng-pattern="/^[a-zA-Z\d\-\_]+$/" Even after trying to remove the escape characters for - and _, the outcome remains the same with the classes ng ...

The issue with AngularJS ng-show and $timeout functionality not functioning as expected

As a newcomer to AngularJS, I recently started an individual project utilizing ng-show and if else statements with $timeout. Despite my efforts, I have been unable to make the answers timeout after being displayed for a few seconds. I've tried various ...

Removing a row from a table in AngularJS connected to FireBase

I am currently facing an issue where the function fails to work when attempting to delete a row. My goal is to be able to remove a specific row from the table by clicking on the red button. Here is the link to my plunker code In index.html, I have includ ...

Conduct a unit test to verify that a function successfully connects to an API and accurately stores the retrieved data in a variable

Currently, I am working on creating a unit test for my writing and JavaScript code. This area is still challenging for me, so I am in the process of learning how to do it correctly. The specific function I am focusing on makes an API call and then assigns ...

Switching the input of data from a string format to a date format

One of the components in my registration form requires the user to input their start date. I am currently utilizing a MEAN Framework, specifically AngularJs for the front end development. Progress so far: Initially, I attempted using the code snippet bel ...

Bidirectional data flow in AngularJS Directives

In an effort to create a dynamic form with different "widgets" based on field types and parameters stored in a database, I have been exploring directives for handling layout changes in response to various scenarios. After experimenting with some examples, ...

Challenges with Angular directive scopes

My current task involves taking an existing template and Angularizing it. I am dealing with 3 directives: a card, a card-header, and a card-body: <card> <card-header title="My Card"> <input type="text" ng-model="userSearch" /&g ...

Creating Dynamic Tags in AngularCreating Tags Dynamically with Angular

I'm exploring the idea of dynamically creating a form by utilizing an array filled with different directive names $scope.components = ["textbox", "textbox", "radio", "checkbox", "label"]; My goal is to generate tags using these names in Angular. For ...

AngularJS: Working with a directive within the UI-Bootstrap modal

I am facing a challenge in trying to invoke a directive from within a modal that is generated using the $dialog service. This directive should also have access to the buttons inside the modal and be able to override their ng-click functionality. Below is ...

Tips for improving performance with ng-repeat directive?

I have encountered some performance issues while using socket.io with the ng-repeat directive in Angular. The application slows down significantly when receiving a large amount of data from the backend, making it impossible to interact with the app. What w ...

Issue with ng-required not validating on iOS in AngularJS

I have been attempting to utilize the ng-required directive in a form. All I did was include ng-required="true" on my input field. When testing in Chrome, upon clicking submit it correctly prevents submission and prompts the user to fill in the required f ...

Leverage the Power of AngularJS to Harness Local

I am currently developing an application using AngularJS. However, I have encountered an issue when trying to use localstorage. Here is my code snippet: var id = response.data[0].id; var email = response.data[0].email; localStorage.setItem('userId&ap ...