Angular Jasmine error: Attempting to broadcast within a timeout when 'undefined' is not an object

Here's a function I've been working with:

 $scope.doIt = function( x, y )
 {
   $timeout( function ()
   {
     $rootScope.$broadcast( 'xxx',
     {
        message: xxx,
        status: xxx
     } );
   } ); 
 }

The function appears to be functioning correctly. However, when I tried to write a test for it, I encountered some difficulties.

describe( 'test doIt function...', function ()
      {
        var $rootScope, $timeout;

        beforeEach( inject( function ( _$rootScope_, _$timeout_ )
        {
          $rootScope = _$rootScope_;
          $timeout = _$timeout_;
          spyOn( $rootScope, '$broadcast' );
          spyOn( scope, 'doIt' ).and.callThrough();
        } ) );

        it( 'test broadcast will be called', inject( function ()
        {
          var testObj = {
            message: 'test1',
            status: 'test2'
          };

          scope.doIt( 'test1', 'test2' );

          expect( $rootScope.$broadcast ).not.toHaveBeenCalledWith( 'xxx', testObj );

          $timeout.flush();

          expect( $rootScope.$broadcast ).toHaveBeenCalledWith( 'xxx', testObj );

        } ) );
      }
    );

This resulted in the following error:

TypeError: 'undefined' is not an object (evaluating '$rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, $location.$$state, oldState).defaultPrevented')

Why is this happening? What am I doing wrong? The function and test work fine without $timeout.

Thank you in advance for any assistance.

:)

Edit: Another broadcast seems to be causing this issue. Hmm

Answer №1

My solution involved resolving the issue through the application of preventDefault

spyOn($rootScope, '$broadcast').and.returnValue({preventDefault: true})

Answer №2

Issue -

The Angular framework is attempting to trigger the $broadcast function and expects an object in return with a defaultPrevented property.

However, due to

spyOn( $rootScope, '$broadcast' );

command within the beforeEach section, the actual execution of the $broadcast function is prevented, resulting in the absence of an object containing the defaultPrevented property.

Resolution -

To resolve this issue, relocate the

spyOn( $rootScope, '$broadcast' );
command from the beforeEach section to the it block just before scope.doIt( 'test1', 'test2' );.

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

Tips for sending multiple values to a jquery dialog box

I am seeking assistance with passing multiple values to a jQuery dialog box and displaying them in a table within the dialog box... The HTML content is being rendered in the dialog box through an AJAX call. Here is my AJAX call: $.get(url, function (dat ...

The de-duplication feature in webpack is not functioning properly when the splitChunks cacheGroups commons option is activated

In my lerna project, I have two identical packages named p1 and p2. Both p1 and p2 utilize a 3rd party package - in this case, eosjs@beta, which is approximately 50KB in size. When I incorporate p1 into an example react project, the package size increase ...

Enhancing the Performance of Asp.net MVC SPA App through Server-Side Rendering

We are aiming to optimize the performance of our single page application built in asp.net mvc. The current framework consists of: Server-side Asp.net mvc communicating with an SQL Database Client-side SPA developed using JS/Html5 + requireJS and KendoUI ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

Combining various postponed JavaScript file imports in the HTML header into a single group

I've been facing an issue with my code structure, particularly with the duplication of header script imports in multiple places. Every time I need to add a new script, I find myself manually inserting <script type="text/javascript" src=&q ...

Learn how to display JSON data sent from the server on a webpage

I'm just starting out with jquery. I have an api called '/categories' that gives me a json object of categories. The response looks like this: [ { name: "Laptop deals", slug: "laptop-deals", imageURL: "image.jpg", id: 1 }, { name: "Fashion ...

The conversion of a newline in an Angular page is done using &lt;br/&gt tag

Here is a function I have: setLocalVariableOnAccepted(ogp, hb, responseJson) { if (responseJson.ofgp === undefined) { this.ogpStatus = 'orange'; this.ogpStatusMsg = responseJson.ofgp + ', <br/> No change. Previous va ...

How can we rearrange the positions of three items in an array?

I am dealing with a function that returns an array of objects structured like this const allGreen = _.filter( sidebarLinks, side => !isServicePage(side.slug.current) ); https://i.stack.imgur.com/dR8FL.png I am attempting to rearrange the positions of ...

What is the best way to update a nested property in an object?

Consider the following object: myObject{ name: '...', label: '...', menuSettings: { rightAlignment: true, colours: [...], }, } I want to change the value of rightAlignment to fals ...

Ways to switch visibility based on user's selection

Currently, I am working on a project that involves a select form with multiple options. However, I need to display a specific div only when a particular option is selected. Can anyone suggest the best solution for this scenario? Your guidance would be grea ...

Refresh the page using a promise in Angular after a delay of 3 seconds

Currently, I am working on enhancing the functionality of the login page. In case a user enters an incorrect login and password combination, my goal is to have the page automatically reload after 3 seconds. Despite my best efforts, I have encountered chall ...

What is the best way to make text appear as if it is floating in Jade or HTML?

Currently, I am facing an issue with a Jade file that displays an error message when a user tries to log in with incorrect credentials. The main problem is that this error message disrupts the alignment of everything else on the page, as it is just a regul ...

Creating a rhombus or parallelogram on a canvas can be easily achieved by following these simple

I'm new to working with the canvas element and I want to create some shapes on it. Can someone provide me with guidance on how to draw a Rhombus or Parallelogram on a canvas? Something similar to what is shown in this image: https://i.stack.imgur.c ...

javascript - the dropdown text remains static

Two dropdown fields are present: DropDownA and DropDownB, along with a checkbox. When the checkbox is checked, DropDownA will mirror the text, value, and selected index of DropDownB before becoming disabled. The issue at hand: Although the attributes ca ...

What specific files from the Kendo core are required for utilizing Mobile and Angular functionalities?

After browsing through similar questions, I couldn't find a solution. Currently, I am experimenting with Kendo (open source core for now) in a Visual Studio Cordova project. Initially, disregarding Cordova, I am focusing on setting up a basic view wit ...

Design a button in d3.js that toggles the visibility of a rectangle and text

Looking to use d3.js to create a simple list from data in a box, complete with a button to toggle the visibility of the box and its content. Ran into two errors during implementation: 1) The list is starting at item 2 for some reason - where's the fi ...

Tips for showing all percentages on a Google PieChart

I'm currently encountering two issues. How can I ensure that the entire legend is visible below the graph? Sometimes, when the legend is too large, three dots are added at the end. Another problem I am facing involves pie charts. Is there a way to d ...

Converting AngularJS ng-pluralize into a custom component

AngularJs ng-pluralize issue in component with model updates. ng-pluralize works fine without component The pluralize in index.html updates correctly when the model is updated, but the one in the component does not update, even though the variable in the c ...

Issue with Tinymce Editor: Content does not refresh when clicking another button within the form

I have a form set up as shown below: <form method="post" action="example.com" id="form"> <textarea id="content">{{$content_from_database}}</textarea> <button type="submit">Update</button> </form> Within the form, I ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...