Error: Unable to define $scope function in Angular and Jasmine integration

I am currently working with a controller

var videoApp = angular.module('videoApp', ['videoAppFilters', 'ui.unique', 'angularUtils.directives.dirPagination']);
videoApp.controller('VideoCtrl', function ($scope, $http, $filter, cacheLoader, $rootScope) {

    $scope.setPageSize = function (pageSize) {
        $scope.pageSize = pageSize;
        return $scope.pageSize;
    };

    $scope.addFavorite = function (data, key) {
        localStorage.setItem(key, data);
        $scope.videos = $filter('articleFilter')(data, $scope.allData);
        return alert(key + " "+ data + " was added to your favorite list.");
    };

    $scope.addSelectedClass = function (event) {
        if($(event.target).hasClass("selected") == true)
        {
            $(event.target).removeClass("selected");
        } else {
            $(".selected").removeClass("selected');
            $(event.target).addClass("selected');
        }
    };

    $scope.filterArticles = function (category) {
        $scope.videos = $filter('articleFilter')(category, $scope.allData);
    };

    $scope.pageSize = 12;

    cacheLoader.load('http://academy.tutoky.com/api/json.php', true, function () {
        $scope.allData = $rootScope.allData;
        $scope.videos = $rootScope.videos;

        if(localStorage.getItem('category')) {
            $scope.videos = $filter('articleFilter')(localStorage.getItem('category'), $scope.allData);
        } else {
            $scope.videos = data;
        }
    });

});

In addition, I have set up a test scenario

describe('Check if VideoListCtrl', function() {
    beforeEach(module('videoApp'));

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

    beforeEach(inject(function ($rootScope) {
        $scope = {};
        controller = $controller('VideoCtrl', { $scope: $scope });
    }));

    it('exists', function() {
        expect(controller).not.toBeNull();
    });

    it('set page size', function () {
        expect($scope.setPageSize(12)).toEqual(12);
    });


});

I am facing an issue while trying to test the functionality of my controller methods. Jasmine is throwing an error during the second test:

TypeError: undefined is not a function

The problem seems to be related to the line $scope.setPageSize(12). I followed the Angular docs tutorial which used scope methods in a similar way, but for some reason, it's not working in my case. Can anyone provide insight into why this might be happening?

Answer №1

When working with Jasmine, it's important to remember that 'it' and 'describe' are functions.

If you need to test something within $scope, make sure that your 'it' functions have access to the variable.

To update your test case, consider the following:

describe('Check if VideoListCtrl', function() {
    //Add an initialize here:
    var $scope = null;
    beforeEach(module('videoApp'));

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

    beforeEach(inject(function ($rootScope) {
        //Create a new $scope
        $scope = $rootScope.$new();
        controller = $controller('VideoCtrl', { $scope: $scope });
    }));

    it('exists', function() {
        expect(controller).not.toBeNull();
    });

    it('set page size', function () {
        expect($scope.setPageSize(12)).toEqual(12);
    });
});

You can also refer to this information in the angular document.

I hope this solution works for you! : )

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

"Visualizing data with Highcharts: Utilizing percentages in a basic bar chart

I am working on a basic 1-series bar chart with nominal values for each bar. While I am able to plot it with data labels and axis showing the value of each bar, my goal is to display the percentage of the total series on these labels while keeping the nomi ...

Include a Vue component within another Vue component in a Laravel application using VueJs

I've recently integrated Vue.js into my Laravel project and encountered an issue when trying to call a component within another component. After running the command npm run dev, I received a webpack error. Here is the code snippet from my parent comp ...

Implement functionality in AngularJS to automatically switch focus to the next input field when the maximum character length is reached, and return focus to the previous input field when the

Task at Hand I am tasked with creating 3 input fields, each with a maximum character length of 5. The requirement is that when the 5th character is entered in an input, the cursor should automatically move to the next input field. Similarly, when the firs ...

Problem with autocomplete functionality in Angular Material's md-contact-chips

Having some trouble with the autocompletion feature of md-contact-chips. I want to capture the $query as soon as someone starts typing. HTML <md-contact-chips ng-model="members" md-contacts="querySearch($query)" md-contact-name="fullname" ...

What is the best way to accomplish this task with promises (using the Q library)?

I am currently working on an app using express.js and mongodb. My goal is to fetch all posts if the database is available, otherwise an error will be thrown. I am utilizing the Q package for promises, but I am struggling to implement the desired functional ...

Prevent rendering a file in node.js using ejs if it cannot be found

I have a specific folder structure under the views directory, containing an EJS file named profile_60113.ejs views docs profile_60113.ejs To dynamically render the file based on the groupID (where data.groupID == 60113), I use the following c ...

What might be causing res.download to retrieve a zip file that is empty?

Using expressjs for my app development, I have created a service to download files on the client side using res.download(filepath, filename). The following is the code snippet of my service: router.route('/downloadFile').get(function(req,res){ ...

CFGRID Binding Issue: Element Not Located in CF11 Compared to CF2018

After spending some time tinkering with this issue, I finally found a solution that worked for me. I decided to share it here in the hopes that it might help others save some time. In ColdFusion 11, my binding parameter looked like this: <cfset args.b ...

Posting values using AJAX in PHP - A guide

test.html <html> <!-- To access the complete PHP-AJAX tutorial, please visit http://www.php-learn-it.com/tutorials/starting_with_php_and_ajax.html If you found this tutorial helpful, a backlink to it would be greatly appreciated. ...

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

Passing a variable between functions in JavaScript: Tips and tricks

let chart; let data = new Array(); function handleClick() { data = document.getElementById('graph:hi').value; alert(data); } let chartData = new Array(66, 15, 2.5, 21.9, 25.2, 23.0, 22.6, 21.2, 19.3, 16.6, 14.8); alert(chartData); jQuery ...

Follow button on LinkedIn is secure with Google Chrome's Content Security Policy set to script-src report-sample

Having an issue trying to add a LinkedIn Follow button to the website. It works perfectly in Firefox, but is not functioning in Chrome. The Console displays the following error: The source list for Content Security Policy directive 'script-src&apos ...

"Enhanced file manager: Elfinder with multiple buttons to seamlessly update text input fields

Every button is responsible for updating the respective element: <input type="text" id="field" name="image" value="<?php echo @$DuzenleSonuc[0]['image']; ?>" /> I need to ensure that each button updates the correct field: onclick ...

Utilizing NextJS to Call the Layout Component Function from the Page Component

I can't seem to find an answer to this question for Next.js after searching online. While there are solutions available for React, I don't think they will work in the Next.js framework. My application is essentially a shop with a navigation menu ...

Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" fo ...

Utilizing Vue.js: Disabling button on image carousel when there is no "next" photo accessible

This is my initial experience with Vue. I am attempting to assemble a slideshow using an array of images. I have successfully managed to disable the "previous" button when the user reaches the beginning of the slideshow, but I am encountering difficulties ...

A guide to transferring modules between component files in JavaScript

My query pertains to the handling of imports in web pages. When a file is imported into another, do the declarations and imports from the imported file become available in the file where it is being imported? A suggestion was made for me to import a compo ...

differences in opinion between JavaScript code and browser add-ons/extensions

As the owner and developer of an e-commerce website, I find that potential customers often contact us regarding ordering issues. Upon investigation, we consistently discover that the problem is caused by JavaScript errors. We frequently check their browse ...

Unable to load images on website

I'm having trouble showing images on my website using Node.js Express and an HBS file. The image is not appearing on the webpage and I'm seeing an error message that says "GET http://localhost:3000/tempelates/P2.jpg 404 (Not Found)" Here is the ...