Attempting to assign parameters in $routeChangeError testing is unsuccessful

Currently, I am in the process of testing the code snippet below:

$rootScope.$on('$routeChangeError', function(event, current, previous, rejection) {
    if(rejection === 'Unauthenticated') {
        $location.path('/');
    }
});

This is the test I have set up:

it('is expected to detect unauthorized route changes and redirect to login page', function() {
    spyOn(this.$location, 'path');

    this.$rootScope.$emit('$routeChangeError', { event: null, current: null, previous: null, rejection: 'Unauthenticated' });

    expect(this.$location.path).toBe('/');
});

However, I noticed that when I pass parameters to $emit, they do not reach the other end as expected. The only populated parameter is 'event', while everything else turns out to be undefined.

The route definition is as follows:

    .when('/welcome', {
        controller: 'main.controller',
        templateUrl: '/welcome.html',
        resolve: { 'authFilter': 'oauthFilter.factory' }
    });

Additionally, the authFilter code snippet appears like this:

(function(mainModule) {
    'use strict';
    mainModule.factory('oauthFilter.factory',
        ['$location', '$q', 'authentication.service',
        function($location, $q, authenticationService) {
            if(authenticationService.isAuthenticated()) {
                return true;
            }
            return $q.reject('Unauthenticated');
        }
    ]);
})(angular.module('main'));

I have attempted to create the controller, inject $q.reject('Unauthenticated'), then apply the scope. Unfortunately, this approach does not trigger the event at all.

Any insights on what I might be overlooking? I appreciate your help in advance.

Answer №1

To trigger the event, the arguments must be passed to $emit individually instead of as one object. For example:

this.$rootScope.$emit('$routeChangeError', null, null, null, 'Unauthenticated');

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

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

Javascript did not provide any prompt

I can't seem to get the function to run when I click the link, it only takes me to the link address. (The final alert() function is not executing). I really need that alert message, what am I missing? Below is my code: <html> <head> ...

Retrieve JSON data from an external website

I am looking to display the number of players currently playing on a different poker website on my own site. The necessary data is provided in JSON format by this link (tournaments.summary.players). I have tried using a .getJSON request, but it seems like ...

Is it possible to convert an object with properties of equal length into a list of objects using JavaScript?

I am working with an object that has multiple keys, each containing a list of equal length: myobj = { 'key1' : [1, 2, 3], 'key2' : ['a', 'b', 'c'], 'key3' : [true, false, true], .. ...

Encountered the issue: "Received the error message 'MongooseServerSelectionError: Server selection timed out after 30000 ms.'"

I encountered the following error: MongooseServerSelectionError: Server selection timed out after 30000 ms while working with MongoDB Atlas. I attempted changing the useUnifiedTopology setting to false, which prevented my application from crashing. However ...

What is the best way to transfer form data to another function without causing a page refresh?

Currently, I am in the process of developing a series of web applications using REACT JS. One specific app I am working on involves a modal that appears upon a state change and contains a form where users can input their name along with some related data. ...

Angular - Uploading Files

Within my $scope.accept function, I am attempting to upload some files to my server. The process works fine when using the tag in my HTML. However, I wish to prevent the page from redirecting and instead handle this with AJAX in my controller. When tryin ...

When using RS256 with JWT, the private key will not be accepted

I've been attempting to generate a JWT using 'jsonwebtoken' with RS256. The keys were generated using the following command: ssh-keygen -t rsa -b 4096 -m PEM -f <filename> The private key output appears as follows: -----BEGIN RSA PRIV ...

Unable to invoke function from code-behind using PageMethods - error undefined

I am in the process of creating a website where users can customize their own cakes. Each cake comes with a base price and various options that may incur additional charges. These additional prices are stored in the database and can be retrieved using the ...

Troubleshooting issue with Highcharts 3D rendering after using setState()

When working on implementing a 3d pie chart in React using react highchart, I encountered an issue. Whenever I utilize this.setState() inside the lifecycle method componentDidMount(), the 3d chart shifts from its original position to the right diagonally. ...

Issue with ng-show toggle functionality not functioning correctly within a custom directive

I am facing an issue with my directive that is responsible for displaying the sidebar in my application. I have tried to implement code that would toggle the content inside the sidebar when triggered, but unfortunately, nothing happens when I attempt to to ...

MongoDB Stitch retrieves all data fields

Can anyone help me with my MongoDB query issue? I've recently started working with mongoDB and I'm having trouble getting just one field back for all my documents. var docs = db.collection("articles").find({}, { _id: 0, title:1}).asArray(); De ...

Ensure that the div remains within the viewport

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Tit ...

Is there a way to make the image above change when I hover over the thumbnail?

Seeking assistance with JavaScript to enable changing thumbnails on hover. As a newcomer to JavaScript, I'm struggling to grasp how to achieve this effect. I've already implemented fancybox for gallery functionality. Below is the HTML and CSS f ...

Loading content within the designated element

<div class="col-sm-6" id="ajaxform"></div> <!-- begin snippet: js hide: false --> <!-- language: lang-html --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul id="accordio ...

The initial value set for the innerHTML property of a div element

I have a requirement in my application where I need to confirm if the container div is empty before adding specific text elements to it. The innerHTML of this div is frequently created and removed within the app, so it's crucial to validate its emptin ...

Ensure that the div automatically scrolls to the bottom when it is loaded, and also when new data is added - using angular

My goal is to replicate the functionality of the iPhone's "Messages" app on a web application using AngularJS or any other JavaScript framework. Each message will be contained in a div element within a larger container. When a new message is added, I ...

Using async/await in a for loop | The await keyword can only be used inside an asynchronous function

I've been attempting to execute the following code: async function verifyExistingUsers(db, users) { return new Promise((resolve, reject) => { var companies = [] for (const [index, user] of users.entries()) { let comp ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

Building a new Vue.JS component inside of an existing parent component

Trying to create a nested component in VueJS has been a bit challenging for me. I have attempted something like this, but unfortunately, it doesn't seem to work as expected (the child component does not display anything): I am interested in exploring ...