Troubleshooting $scope.$on unit testing - event not getting detected

In one of my controllers, I have implemented a simple $scope.$on function:

app.controller('MyController', function($scope) {
    $scope.$on("myBroadRcvr", function(event, data) {
        $scope.name = data.name;
        $scope.empID = data.empID;
    });
});

To test this functionality, I attempted unit testing in the following manner:

describe('MyController', function () {
    var $scope, super_controller;

    beforeEach(function(){
        module('myApp');

        inject(function($rootScope, $controller){
            $scope = $rootScope.$new();
            spyOn($scope, '$on');

            super_controller = $controller('MyController', {$scope: $scope});            
        });
    });

    it('should successfully receive name as "test"', function (){

        var myData = {name: 'test', empID: 'eg7gg'},
        var sub_scope = $scope.$new();

        sub_scope.$broadcast('myBroadRcvr', myData);

        expect($scope.$on).toHaveBeenCalled();
        expect($scope.name).toBe('test');
    });
});

However, when running the test, the following error occurred:

Expected undefined to be 'test'.

Answer №1

When dealing with the sub_scope as a child of $scope, keep in mind that using $broadcast will send the event downwards through the scope hierarchy. This means that the listener on the parent scope ($scope) won't capture it. To address this, use $emit instead:

sub_scope.$emit('myBroadRcvr', myData);

To learn more about $broadcast, refer to the documentation here:

This function dispatches an event name downwards to all child scopes (and their children), notifying any registered $rootScope.Scope listeners.

(In contrast, $emit sends events upwards.)


Additionally, your code contains a minor syntax error: the line

var myData = {name: 'test', empID: 'eg7gg'},
should end with a ;.

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

Combining arrays to append to an array already in place

I have implemented the rss2json service to fetch an rss feed without pagination support. Instead of a page parameter, I can utilize the count parameter in my request. With this setup, I am successfully able to retrieve and display the feed using a service ...

What causes the _.sum() function in lodash to not work with objects in Vuejs?

I've encountered an issue where using Vuejs and Lodash in conjunction with a computed property that calculates the sum of a property in a collection results in unexpected behavior. Instead of summing the values, it seems to concatenate the string [obj ...

The Stepper StepIconComponent prop in MUI is experiencing issues when trying to render styles from the styles object, leading to crashes in the app

Struggling to find a way to apply the styles for the stepper component without using inline styles. I attempted to replicate Material UI's demo, but encountered an error. The code from Material UI's demo that I want to mimic is shown below: http ...

Exploring the potential of $scope within $timeout in AngularJS

I am attempting to display a default message on a textarea using AngularJS. Some of the values I want to include require the use of $timeout to retrieve the values. The message does not appear to show up with the following code: <textarea class="t ...

Is it possible for an HTML5 video element to stream m3u files?

Hey there, I'm currently working on integrating a video player using the HTML5 video tag. The content I have is being provided by Brightcove and is in the form of an m3u file. Is it feasible to play this video using the HTML5 video tag? My understand ...

Encountering the error `ReferenceError: document is not defined` when trying to deploy a Next.js project on Vercel

I recently worked on a Next JS project and deployed it to Vercel. Initially, everything was running smoothly, so I didn't check the website status for a while. I was just developing it locally and pushing updates to GitHub. However, when I finally rev ...

Exploring the potential of utilizing functions in express.js to take advantage of the "locals"

Having experience with Rails/Sinatra, I am accustomed to using helper functions in my view files. However, incorporating this functionality into express.js has proven to be quite challenging. You can include locals automatically like this... app.set("nam ...

Adjust the class based on the model's value in AngularJS

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'} html <div class="variable" ng-repeat="item in items">{{item}} </div> ...

How to insert a span element within a link tag in Next.js/React.js

Looking to create a breadcrumb using microdata in a Next.js and React.js project. Initially, I tried the following: <li itemProp="itemListElement" itemScope itemType="https://schema.org/ListItem"> <Link href={'/index&a ...

Exchange of Fusion Chart

Attempting to perform a fusion chart swap with asp has proven to be challenging. The alternative approach involves rendering the fusion chart first and then using onmousedown to replace the chart with an image. However, this method is also encountering i ...

default selection in AngularJS select box determined by database ID

Here is the scenario: ... <select ng-model="customer" ng-options="c.name for c in customers"> <option value="">-- choose customer --</option> </select> .... In my controller: $scope.customers = [ {"id":4,"name":"aaaa", ...

Exploring the dynamic changes in user authentication state with Angular Fire subscriptions

At the moment, I have been listening to authentication state changes in my ngOnInit method of my AppComponent: export class AppComponent implements OnInit { constructor(public fireAuth: AngularFireAuth) { } ngOnInit(): void { this.fireAuth.auth ...

Unable to reach any path within my template directive

Currently, I am working on a directive that fetches news data using the HTTP GET method based on specific options. import publicListTpl from './public-list.html'; (() => { angular .module('news.crud.directives', []) ...

White border appears when hovering over MUI TextField

I've been troubleshooting this issue for what seems like an eternity. I've combed through Chrome's inspect tool, searching for any hover styles on the fieldset element, but to no avail. Here's my dilemma... I simply want a basic outline ...

Screen readers are unable to "read" text that is identified through aria-describedby

When enhancing my web application for accessibility, I encountered a challenge. I have implemented two required fields in a form that should display separate error messages as spans. To accomplish this, I am utilizing aria-invalid to signal when the fields ...

Exploring the functionality of Angular.js through QUnit testing

Is it possible to integrate angular.mock.inject() with QUnit instead of Jasmine? In the provided code snippet, angular.mock.dump is defined, but unfortunately angular.mock.inject remains undefined. <!DOCTYPE html> <html ng-app="mymodule"> & ...

How can you display an alert message when new data is successfully added to a database using ajax?

In my web application, I have implemented a functionality to display an alert message when new data is successfully inserted into the database. The Ajax code below is responsible for sending a request to the EditDeleteLecture.php file. However, a challenge ...

How to toggle the selection of all checkboxes in an AngularJS ng-repeat object array

Check out this Fiddle Example In my table, each row contains a checkbox and there is also a checkbox to check all rows and send the ID of the selected/all rows as JSON object. I have an array of objects from the server-side response (with pagination enab ...

Retrieve the location of the selected element

We are faced with the challenge of determining the position of the button clicked in Angular. Do you think this is achievable? Our current setup involves an ng-grid, where each row contains a button in column 1. When the button is clicked, we aim to displ ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...