Error in Angular unit testing: The function myMethod is not recognized in this.router

I am currently working on unit testing in Angular 4.0.0.

Here is my test case:

test.spec.ts :

// Test Suite of Que-Again features
            describe('QueueAgainComponent features', () => {

                it('should navigate', () => {
                    comp.goToPrevious(); // THIS IS WHERE THE ISSUE LIES
                    expect(mockRouter.navigate).toHaveBeenCalledWith(['/home/pilote'], {skipLocationChange: true});
                    sharedclientService.user.isAdviser = true;
                    comp.goToPrevious();
                    expect(mockRouter.navigate).toHaveBeenCalledWith(['/home/advisor'], {skipLocationChange: true}); 
       });

In the configuration part, I have mocked my RouteNavigator service like this:

let mockRouter = {
            navigate: jasmine.createSpy('navigate')
        };
    providers: [{provide: RouteNavigator, useValue: mockRouter}]

My test fails with the following error:

TypeError: this.router.myMethod is not a function

The log file indicates that the problem is at line 98:18, which corresponds to this line:

comp.goToPrevious();

The implementation of goToPrevious() in my component looks like this:

goToPrevious() {
        this.routeNavigator.myMethod();
      }

The routeNavigator refers to a custom service used for handling custom redirection, defined as follows:

**Route-navigator.service.ts**
    import { LoginComponent } from '../../login/login.component';
    import { SharedclientService } from '../../service/sharedclient.service';
    import { Injectable } from '@angular/core';
    import { Router, ActivatedRoute } from '@angular/router';

    @Injectable()
    export class RouteNavigator {
      constructor(private router: Router, private sharedclientService: SharedclientService, private activatedRoute: ActivatedRoute) { }

      accessAdvancedSearchFromRegistration = false;
      accessSyntheseWhileGdfaShown = false;
      track360View = false;
      oldUrl: string;

      private rdvReferer: string;
      public navigateTo(url: string) {
        this.oldUrl = this.router.url;
        this.router.navigate([url], { skipLocationChange: true });
      }

      public myMethod()  // MY METHOD IS HERE
     {

        if(this.sharedclientService.user != null && this.sharedclientService.user.isAdviser==null){
            this.navigateTo('/home/blank');
            this.sharedclientService.setCurrentRole('');
        }

        else  if (this.sharedclientService.user != null && this.sharedclientService.user.isAdviser) {
          this.navigateTo('/home/advisor');
          this.sharedclientService.setCurrentRole('VENDEUR');
        } else {
          this.navigateTo('/home/pilote');
          this.sharedclientService.setCurrentRole('PILOTE');
        }
      }

      public goToNextAdvancedSearch() {
        if (this.accessAdvancedSearchFromRegistration || !this.sharedclientService.user.isAdviser) {
          this.navigateTo('/home/registration');
        }
        else {
          this.track360View = true;
          this.navigateTo('/home/view-360');
        }
      }

      public exitAdvancedSearch() {
        if (this.accessAdvancedSearchFromRegistration) {
          this.navigateTo('/home/registration');
        }
        else {
          this.goToHomeAccordingToProfile();
        }
      }

      goToRdv(url?:string) {
          if(!url)
        this.rdvReferer = this.router.url;
          else this.rdvReferer=url;
        this.navigateTo('/home/appointment');
      }

      exitRdv() {
        this.navigateTo(this.rdvReferer);
      }
      goToBlank() {
          this.navigateTo('/home/blank');
        }
      public url() {
        return this.router.url;
      }
     }

Any suggestions on how to resolve this issue or deal with it?

Answer №1

When you call goToPrevious(), it triggers this.router.myMethod();

Without expanding the router, I am not familiar with this in the Angular Router module!

UPDATE your dummy data should include the following:

let dummyRouter = {
  navigate: jasmine.createSpy('navigate'),
  myMethod: () => {/* add mock implementation here */}
};
providers: [{provide: DummyNavigator, useValue: dummyRouter}]

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

Eradicate lines that are empty

I have a list of user roles that I need to display in a dropdown menu: export enum UserRoleType { masterAdmin = 'ROLE_MASTER_ADMIN' merchantAdmin = 'ROLE_MERCHANT_ADMIN' resellerAdmin = 'ROLE_RESELLER_ADMIN' } export c ...

Having trouble transforming my JSON file into a JavaScript object

I have a JSON file with the following structure: { "branding": { "body": { "header_text_color": "#224466", "body_text_color": "##224466", "background_color": &quo ...

execute the middleware function within the router

I've integrated sessions in my express.js application using Mozilla's client-sessions and I'm encountering an issue. My post and get requests are in router.js, while the middleware is in app.js. When I try to run it, I receive the following ...

Taunting a specific occurrence inside a group

Good evening, I am currently in the process of developing tests for the TypeScript class shown below. My goal is to create a test that ensures the postMessage method of the internal BroadcastChannel is called. However, I am facing difficulties in setting ...

Having trouble getting smooth scrolling with easing to function properly

I'm facing an issue with a JQuery function that is supposed to enable smooth scrolling using JQuery easing, but for some reason, it's not functioning correctly and I'm unable to pinpoint the error. Here is the code for the function: $(func ...

Using React JS, how to easily upload a CSV file to Amazon S3 with your AWS credentials

Seeking guidance on how to utilize AWS credentials to upload a CSV file using React S3 Uploader. The code snippet I've tried so far is as follows: import React, { PureComponent } from "react"; import ReactS3Uploader from "react-s3-uploader"; sav ...

Angular 10 and Typescript: Variables assigned within the change event become undefined

In my code, I initialize an Algolia input and set an onchange event to it. This initialization takes place in a service. algolia_data; random_var; this.http.post<any>('APIENDPOINT', formData).subscribe(data => { instance = places({ ...

Javascript file containing prohibited characters disrupting form functionality when linked with Jquery

Having some trouble with these files - HTML form, PHP processor, and JavaScript. The browser is showing errors like U+12AF for illegal characters in the JavaScript file. Spent 1.5 hours on this already and feeling frustrated. --submit.js-- $(docume ...

Deactivating Google Map Clustering for Individual Markers

I'm currently utilizing Angular 4, Google Maps v3, and Marker Clusterer v2 - all of which are the latest versions. I'm attempting to implement a straightforward example found in the official Google Maps documentation (https://developers.google.co ...

Integrating an API with a Discord bot using an embedded link in Discord.js

I am currently in the process of creating a bot that can generate and embed links to display manga titles, tags, and other information based on user-input digits. I have been exploring an API called this and I am eager to learn the most effective method ...

Issue with typography upon initial page load

Hey everyone! I recently completed a crash course in html, css, and javascript within just one month. However, I encountered an issue while using canvas to draw text with a custom font. The font didn't load the first time I ran the code, but strangely ...

Tips for optimizing the performance of an Angular 2 website

I am currently developing a website in Angular 2 and have successfully completed one module which I uploaded to the demo path. However, when I tested it using Google Speed Test, it only received a speed score of 37 on desktop and 32 on mobile. Can anyone ...

Upon page load, the opencart div tab content fails to display

I'm currently using an opencart template, and I'm attempting to display some data from a MySQL table in a div tab. Initially, everything works fine. However, when I reload the browser, it doesn't display the default current div with the MySQ ...

The union type consisting of String, Boolean, and Number in type-graphql has encountered an error

I attempted to create a union type in type-graphql that represents the String, Number, and Boolean classes, but unfortunately, it was not successful. Does anyone have any suggestions on how to achieve this? export const NonObjectType = createUnionType({ ...

"Troubleshooting: Fixing the issue with jQuery datepicker not

After implementing the jQuery Datepicker on a field, I noticed that even though assigning a value to the field shows in Chrome's developer tools... https://i.sstatic.net/We7Ua.png Unfortunately, the assigned value does not show on the front end. I ...

Adding a new array to the start of an HTML list using JavaScript

My object consists of the following: var data = [ {item_name: 'Book', stock: 15}, {item_name: 'Pencil', stock: 15}, {item_name: 'Paper', stock: 3} ]; To display this object in a HTML list, I use the following code snip ...

Transforming a Typescript object into properly formatted JSON data

UPDATE3: This is what I achieved: https://i.sstatic.net/noAlU.png Here's the code I used to retrieve that data from the backend: private extractTrains(res: Response){ let body = res.json(); let trains = body['List of vehicles' ...

Guide on dynamically changing the color of polymer 1.0 paper-button from an array of colors

I have an array called buttonColors that contains a set of colors in hex format. I am looking to create paper-buttons, each with the color from the buttonColors array. How can I achieve this in Polymer 1.0? <template is="dom-repeat" items="{{buttonCo ...

Ways to assign a placeholder to a dropdown menu

I'm trying to add a text placeholder to my selectbox, but all the options disappear when I try to do so. Can someone help me with this issue? Here is the code snippet I'm using: window.onload = function () { $('#slide').editableS ...

How can I use JavaScript to show a div upon clicking an input element?

I am looking to make a block div visible when an input field is clicked. <input class="indifferent" type="radio" name="decision" value="indifferent"> Indifferent </br> <div class="input" style="display: none;"> Please assist with our com ...