Trying out a directive with the use of .$on

I have created a few controllers using the .$on method and have successfully tested them. You can view an example on Plunker: http://plnkr.co/edit/8cwcdPc26PVAURmVFR8t?p=preview

Currently, I am working on a directive that also uses the .$on method in its link function:

app.directive('myDirective', function($rootScope, $timeout) {
    return {
        restrict: 'A',
        replace: true,
        scope: {},
        link: function(scope,element,attrs){

            scope.$on("step1", function(event) {
                $rootScope.$broadcast('step3');
                scope.hidden = false;
                scope.shown = false;
            });
            scope.$on("step2", function(event) {
                scope.msg = '';
                scope.errorCase = false;
                scope.infoCase = false;
            });
            scope.$on("step3", function(event) {
                scope.hidden = true;
            });
        },
        template: 
                        '<div class="wrapper">' +
                            '<p>{{ msg }}</p>' +
                        '</div>'
    };
});

I have written the following test for this directive:

describe('myDirective', function () {
    var $scope, compile, element;

    beforeEach(module('myApp'));

    beforeEach(inject(function ($rootScope, $compile) {
        $scope = $rootScope.$new();
        element = angular.element("<section my-directive></section>");
        $compile(element)($scope);
        $scope.$digest();
    }));

    it('should initialise step1', function (){
        var sub_scope = $scope.$new();
        sub_scope.$emit('step1');
        expect($scope.hidden).toBeFalsy();
        expect($scope.shown).toBeFalsy();
    });
});

However, the test is not running at all and no errors are being displayed. It seems like the approach I took for testing the controller is not correct for the directive. Any suggestions?

Answer №1

When you define a directive, you are essentially creating a new scope for it:

app.directive('myDirective', function($rootScope, $timeout) {
    return {
// ... Your directive code ...
        scope: {}, // This isolates the scope for the directive
// ... More directive code here ...
    };
});

In your testing environment, the $scope variable refers to the parent scope that created the directive. To access the directive's scope within your test, use the 'isolateScope' method. Take a look at this updated plunker for reference.

it('should initialize step1', function (){
    var directiveScope = element.isolateScope();
    var sub_scope = directiveScope.$new();
    sub_scope.$emit('step1');
    expect(directiveScope.hidden).toBeFalsy();
    expect(directiveScope.shown).toBeFalsy();
});

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

Error: Execution exceeded the time limit of 5000 milliseconds - Combination of Protractor and CucumberJS

latest versions: cucumberjs --version 1.2.2 protractor --version 4.0.1 Both were globally installed via npm Ever since I upgraded to a higher version of cucumberJs, I've been encountering this error message: Failures: 1) Scenario: Retrieving recor ...

Load jQuery script after Ajax call has loaded the filter

Currently, I have multiple jQuery scripts running on one page. This specific page includes a product filter that operates using ajax. You can view the product filter at Below is one of the scripts I am utilizing: var $s = jQuery.noConflict(); $s('bo ...

Utilizing AngularJS to display the contents of a MongoDB collection

I have a set of sessions that I want to print out individually using AngularJS. This is my code : collection.find().toArray(function(error,data){ if (error) { // Pass the error to the error handler console.log("Error :" + erro ...

Angular categories are utilized for the specific showing of conditions

How can I, using AngularJS, only display the name of the category once by assigning a previous-category variable to match this condition? Eg. Animals, orc, sea; Animals, dolphin, sea; Animals, lion, land; Fruits, apple, red; Fruits, orange, citric; & ...

Activating the CSS :active selector for elements other than anchor tags

How can I activate the :active state for non-anchor elements using JavaScript (jQuery)? After reading through Section 5.11.3 of the W3C CSS2 specification in relation to the :hover pseudo selector in hopes of triggering the activation of an element, I stu ...

I'm having trouble with an error in my React project on VS Code. Can anyone provide guidance

Could you please explain the meaning of this error message: errno: 'ENOENT', code: 'ENOENT', syscall: 'spawn cmd', path: 'cmd', spawnargs: [ '/s', '/c', 'start', '""', ...

Save the JSON data into a variable inside a React utility component

Currently, I am new to React and facing an issue with fetching data and storing it in a variable. I have been struggling to understand why my SetMovieResponse function is not working as expected. I have tried stringifying the JSON before sending it, but w ...

The first date will only be updated once I select a date for the second time in my modal window

Why won't my modal immediately update when I select a date or time? It only reflects changes after selecting the date for the second time. Any ideas on how to fix this? <div class="item item-input"> <div class="row"> <div ...

I am looking to have the notification "LEVEL X ACCESS GRANTED" appear just one time. It is important to carefully review the entire question for complete clarity

Can you assist me with this code? I am encountering an issue where a congratulatory message is printed every time the user fails to achieve a certain score after initially reaching it. My intention is for the message to only be displayed once when the us ...

Using jQuery to locate and delete multiple attributes from div elements

My goal is to locate all div elements with the class name "comment-like" that also have data-id attributes set to 118603,1234,1234,118601,118597. If a div contains any of these data values, then I want to remove that data attribute. I've attempted th ...

The Vue router fails to navigate to the designated destination

Having an issue with vue-router where routing doesn't work properly when trying to navigate to a child route. { path: '/user', name: 'User', component: User, children: [ { path: 'profile', ...

What is the best way to access CSS variables declared in the root element?

For my React project, I have defined color variables. I want to create my own color palette for the DevExtreme pie chart UI component. :root { --my-pastel: var(--rose) var(--beige) var(--bright-orange) var(--brighter-orange) var(--bright-rose) var(--bright ...

How can I retrieve the first key name from an object in AngularJS?

Can you assist me in retrieving the name "GetToolInfo" from the following object? {"GetToolInfo":{ "Item":[ { "_Key":"DefaultPath", "_Value":"C:\\Users\\vkedarix\ ...

What is the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

Issue: Dependency type ContextElementDependency does not have a corresponding module factory available

After cloning the project from GitLab and running npm install, all dependencies were successfully downloaded. However, upon executing npm start, I encountered an error stating "No module factory available for dependency type: ContextElementDependency." In ...

Trouble with Chakra UI loading Images from local sources

I'm running into issues when trying to load local images using the Chakra UI library in combination with Next.js. <Image src="./homepage/footer/Black.svg" /> Here is the current folder structure: When checking my console, I see the f ...

Utilize Vue's prop system to pass objects between components

Can you help with passing objects as props in Vue? It seems like a simple task, but I'm having some trouble. In my .vue file, I have the following code: <template> <div id="scatter"></div> </template> <script&g ...

Having trouble turning octet-stream response data into a downloadable Zip file

I've been attempting to download a Zip file that contains JSON files through an AJAX GET request. Here is the format of the response headers: Connection: keep-alive content-disposition: attachment;filename=exportedFiles_ 1.6.0_20200731160652.zip Cont ...

How to utilize AngularJS to submit a Symfony2 form

I'm currently working on developing an application with Symfony2 for the backend and considering using AngularJS for the frontend. My plan is to integrate Symfony forms into the project as well. I have successfully set up the form with all the necessa ...

Personalize with ng-class in AngularJS

I am facing an issue with two specific CSS classes, namely .caret .right and .caret .down. This is the code snippet causing the problem: <span> ng-class="{'caret right': checkboxer[mainParent]==true,'caret down': checkboxer[mainP ...