Verifying the invocation of a callback function through the use of $rootScope.$broadcast and $scope.$on

I have been testing to see if a callback was called in my controller.

Controller

(function () {
    'use strict';

    angular
        .module('GeoDashboard')
        .controller('CiudadCtrl', CiudadCtrl);

    CiudadCtrl.$inject = ['$scope', '$interval', '$rootScope','Ciudad'];

    function CiudadCtrl($scope, $interval, $rootScope, Ciudad) {

        $scope.refreshCiudad = refreshCiudad;
        $scope.refreshClima = refreshClima;

        var removeListenerRefreshCiudad = $scope.$on('refreshCiudad', refreshCiudad);
        var cancelIntervalIdClima = $interval(refreshClima, 600000);

        function refreshCiudad() { 
           //...
        }
    }

})();

Testing

beforeEach(inject(eachSpec));

function eachSpec($rootScope, $controller, $httpBackend, $interval, _Ciudad_){

    rootScope = $rootScope;
    scope = $rootScope.$new();
    httpBackend = $httpBackend;
    interval = sinon.spy($interval);

    CodificacionGeograficaService = _CodificacionGeografica_;
    CiudadService = _Ciudad_;

    CiudadController = $controller('CiudadCtrl', {
       $scope : scope,
       $interval: interval,
       Ciudad: CiudadService
    });  
}

it('3. Should call "refreshCiudad" when listening for the "refreshCiudad" event', spec3);

function spec3(){

    sinon.spy(scope, 'refreshCiudad');

    rootScope.$broadcast('refreshCiudad');

    expect(scope.refreshCiudad).toHaveBeenCalled();
    scope.refreshCiudad.restore();
}

However, when trying to emit a $broadcast event, the callback is not being called.

What could I be doing wrong?

Answer №1

Success! I finally got it to work, although the reason behind it eludes me. To make it function properly, I had to encapsulate the callback function for $scope.$on within another function like so:

    function CityController($scope, $interval, $rootScope, City) {

        $scope.updateCity = updateCity;

        // Instead of doing this
        // var removeListenerUpdateCity = $scope.$on('updateCity', updateCity);
        // I approached it this way
        var removeListenerUpdateCity = $scope.$on('updateCity',  function(){
            $scope.updateCity(); // Surprisingly, this did the trick!
        });

        function updateCity() { 
           //...
        }
    }

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

Why is it necessary in JavaScript to reset the function's prototype after resetting the function prototype constructor as well?

Code is often written in the following manner: function G() {}; var item = {...} G.prototype = item; G.prototype.constructor = G // What is the purpose of this line? Why do we need to include G.prototype = item before resetting the prototype? What exact ...

Transmitting an HTML file along with JSON data and enabling the browser to refresh the JSON data without reloading the entire

I'm currently working on a project involving a browser-server program where the browser sends an http get request to ''. The server is expected to return both an HTML page and a JSON response. I attempted using res.render(), passing the JSON ...

My JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...

Making a Zoom effect using p5.js

I have searched for a solution to this question multiple times, but none of the answers I came across seem to work for me. Currently, I am able to allow the user to scale an image with a simple scale(factor) call. However, now I am attempting to implement ...

Displaying the saved MTRC (markdown-to-react-components) content from the database

I currently have data stored in a database that has been produced using the markdown-to-react-components package as MTRC(content).tree What is the best way to render this content? I've experimented with various approaches, such as dangerouslyInsertHT ...

Showcasing a dynamically created JSON document on a basic web page

Looking for a solution to display the contents of a result.json file generated by my Java tool on a simple website. I am aware that accessing local files directly with JavaScript is not possible, so seeking alternative methods that do not involve using a w ...

Angular Form Validation: Ensuring Data Accuracy

Utilizing angular reactive form to create distance input fields with two boxes labeled as From and To. HTML: <form [formGroup]="form"> <button (click)="addRow()">Add</button> <div formArrayName="distance"> <div *n ...

Unable to transmit an object using ExpressJS

Greetings. I am currently trying to comprehend ExpressJS. My goal is to send a simple object from the express server, but it only displays "cannot get" on the screen. app.get("/", (req, res, next) => { console.log("middleware"); const error = true; ...

The error message "Multiple children error occurs when an empty link in Next.js

Is there a way to successfully implement a <Link /> element without any content inside it in my application? Surprisingly, when I don't provide any content, I encounter the multiple children error, even though the opposite seems to be happening. ...

The clearTimeout function in React stateless components does not appear to be functioning properly

I am facing an issue with a component that I developed. In this component, one value (inclVal) needs to be larger than another value (exclVal) if both are entered. To ensure that the function handling this comparison doesn't update immediately when pr ...

Hoping for a swift ajax response from the identical function

Even though similar questions have been asked multiple times, I have gone through many of them and still haven't found a solution to my specific issue. I am currently using a Wizard Jquery Plugin that triggers a function onLeaveAStepFunction when a s ...

Adding identifiers to columns in DataTables depending on the value of another attribute

I am facing a challenge with inserting the <span> tag into the "salesStatusName" column cell that already contains some data. This should only happen when the value of the last column, "completelyDelivered", is true. However, I do not want to display ...

Adding a default option to my AngularJS select box

React const SnazzyContext = React.createContext(); function App() { return ( <SnazzyContext.Provider value={getList()}> <MenuSideController /> </SnazzyContext.Provider> ); } function getList() { // Function to fetch ...

Which is better: Utilizing Ajax page echo or background Ajax/direct HTML manipulation?

I am facing a dilemma and I could really use some guidance. Currently, I am in the process of developing an ordering system using PHP/Smarty/HTML/jQuery. The main functionality revolves around allowing sellers to confirm orders on the site. My goal is to ...

Tips on finding the key associated with a specific value

When a form is submitted, one of the fields being sent is an ID number instead of the name for easier processing by the server. For example: HTML dropdown select <select ng-model="myColor" class="form-control" ng-options = "color.ID as color.color ...

Creating dynamic and asynchronous JSON structures with JavaScript

Struggling with async JavaScript here. I've got a function called within a jQuery AJAX function, and it looks like there are more async method calls in that function. Currently stuck in this situation. Here's the code snippet triggered by the jQ ...

Determining the installation duration of the React Native screen

Several questions have been asked about this topic, but none of them seem to have a definitive answer. What I am looking to do is calculate the time it takes to navigate to a screen. The timer will start here: navigation.navigate("SomePage") Essentially, ...

Is it possible to utilize JavaScript on a mobile website for item counting purposes?

I have a task at hand that I need help with, and I'm unsure of the best approach to take. The goal is to create a mobile web page that can count items during a specific session. There will be four different items that need to be counted: chicken, cow, ...

Cursor hovers over button, positioned perfectly in the center

I am facing a challenge with implementing a hover function for a set of buttons on the screen. The goal is to display the mouse pointer at the center of the button upon hovering, rather than the actual position of the cursor being displayed. I have tried u ...

Using conditional statements with a series of deferred actions in jQuery

In the scenario where I have chained the $.Deferred as shown below: $.each(data, function(k, v) { promise.then(function() { return $.post(...); }).then(function(data) { if(data)... // here is the conditions return $.post(.. ...