Testing the scope of an Angular directive

Encountering an issue with the unit test

In my code, I have:

describe('test controller', function () {
    var =$compile, scope, rootScope;

    beforeEach(module('myApp'));
    beforeEach(inject(function (_$compile_, _$rootScope_) {
       $compile   = _$compile_;
        rootScope   = _$rootScope_;
        scope        = _$rootScope_.$new();
    }));

    describe('test', function() {
        beforeEach(function () {
            scope.toys = ['toy1', 'toy2'];            
        });
        it('should test directive' , function() {
            var element = $compile('<button type="button"  show-item>See all</button>')($rootScope);
            element.triggerHandler('click');
            $rootScope.$digest();
        });
    });
});

Here is the HTML:

   <button type="button"  show-item>See all</button>

The Directive:

angular.module('myApp').directive('showItem', 
function() {
    return {
        restrict: 'A',
        scope: false,
        link: function(scope, elem, attrs) {                
            elem.bind('click', function() {
                var l = scope.toys.length;
                //other codes
            });
     }
});

When running the unit test, I am encountering an error stating '

undefined' is not an object (evaluating 'scope.toys.length')
.

I am unsure why this error is occurring, as I have specified scope.toys inside the beforeEach function. Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

The reason for this issue is due to compiling with $rootScope which lacks the toys property. It is recommended to utilize the existing scope variable that already contains the toys property.

  var element = $compile('<button type="button"  show-item>See all</button>')(scope);

Check out the live demo here

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

Fixing a CSS animation glitch when using JavaScript

I'm facing an unusual issue with my CSS/HTML Check out my code below: a:hover { color: deeppink; transition: all 0.2s ease-out } .logo { height: 300px; margin-top: -100px; transition: all 0.2s ease-in; transform: scale(1) } .logo:hover { transit ...

Activate the Bootstrap Jquery/Ajax inline editing feature by simply clicking on the Edit button

Seeking recommendations for a way to implement inline editing. When the edit button is clicked, I want the label's content to be replaced with an input text field that can be updated in my MySQL database. This is what my code looks like: <label s ...

Issues with rendering TextGeometry in Three.js

Despite my attempts to replicate the demo code, I am unable to successfully render TextGeometry. The necessary font file is correctly uploaded on the server. var loader = new THREE.FontLoader(); loader.load( 'fonts/open-sans-regular.js' ...

Incorporate query strings into every hyperlink within the application

Let me paint you a picture... I've got this lovely Next.js app that's been around for a while, filled with lines of code we've poured our hearts into. Recently, we decided to spice things up by running some ads and now we are itching to see ...

Exploring Ways to Retrieve Property Names in AngularJS JSON

I need help finding a way to use the property name as the table header in my code example below: <table> <th ng-repeat="auditorium in auditoriums"> {{ auditorium.NAME }} </th> <tbody ...

What could be causing my recursive function to skip over certain parts of my JSON data?

UPDATED TO BE MORE CONCISE Hello, I'm looking for assistance with a recursive function that's not returning the expected values from a JSON object. The goal is to retrieve all "Flow" object IDs where the "Type" is either "Standard" or "Block". T ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

Make sure to always display the status bar and soft keys

Is there a way to set up my ionic app on Android so that the status bar is always displayed at the top and the soft keys are shown at the bottom? I attempted to add this line to the config.xml file, but it didn't work. <preference name="Fullscree ...

Easy Registration Page using HTML, CSS, and JavaScript

In the process of creating a basic login form using HTML and CSS, I'm incorporating Javascript to handle empty field validations. To view my current progress, you can find my code on jsfiddle My goal is to implement validation for empty text fields ...

Utilizing Selenium Page Object for Enhanced Reusability

One aspect of Selenium 2 that I appreciate is how it encourages the use of PageObjects as POJOs and simplifies field instantiation with PageFactory. However, a limitation I have encountered is the reuse of elements across multiple pages. The challenge ari ...

Unable to prevent Protractor from showing file download prompt

Challenge Currently, I'm facing an issue with downloading a file where the "Save as..." dialog pops up when triggering the download. Although I found a potential solution on this Stack Overflow thread, it doesn't seem to be effective in my case. ...

Finding differences between two 24-hour format times using moment.js

Is there a way to compare two times in 24-hour format using the code below? $("#dd_start_timing, #dd_end_timing").on('keyup change keydown', function() { var DutyDayStartTime = $("#dd_start_timing").val().trim();// 13:05 var ...

Help Needed: Adding a Simple Element to jQuery Tabs Script

I recently came across a fantastic jQuery tabs script on a website called Tutorialzine. The link to the article can be found here. As I was implementing this script, I realized I needed to customize it by adding specific classes to certain tabs. Specifica ...

The issue with setting width using % in React Native is causing trouble

While working on my project using expo react native, I encountered an issue with a horizontal scrollview for images. When I style the images using pixels like this: <Image code... style={{width: 350}}/>, everything works fine. However, if I try to ch ...

Testing React Hook Form always returns false for the "isValid" property

When creating a registration modal screen, I encountered an issue with the isValid value when submitting the form. In my local environment (launched by npm start), the isValid value functions correctly without any issues. However, during unit testing us ...

Switching the visibility of rows in a table

Imagine this as my example table: <table> <tr> <td>a</td> <td>one</td> <td>two</td> </tr> <tr> <td>b</td> <td>three</td> <td>four</t ...

Strategies for selecting glyphs in SVG fonts based on their Unicode properties

My goal is to extract specific characters from SVG fonts created for music engraving. Music fonts typically include a large collection of characters (> 3500), but I only require a small subset of them for caching glyphs in compressed form to ensure quic ...

Sending a collection of JSON data objects to a PHP page using AngularJS

Let me illustrate the structure of my JSON data: $scope.a = [{ "email": "keval@gmail", "permissions": { "upload": "1", "edit": "1" } }, { "email": "new@aa", ...

Troubleshooting a configuration problem with Mean-cli

Recently, I've ventured into developing mean based apps. I'm currently following the steps outlined here to configure the app. Despite installing all necessary prerequisites as instructed in the link, I encountered an error while working on Windo ...

Is it a graphics card malfunction or a coding complication? Delving into THREE.JS WebGL

Recently, I created a cool scene using three.js that was running perfectly until today. Strangely, without any changes to the code, I started encountering an error in every major browser - Chrome, Firefox, and Edge. The error message I am seeing is: THREE. ...