Error message when testing Angular Mat Dialog: The function This.dialogref.updatesize does not exist

I am a beginner in working with Angular. I am currently facing an issue while writing a unit test for mat dialog which is resulting in an error.

This is the method in my TypeScript file :

isMobileScreen= Observable<BreakpointState>= this.breakpointObserver.observe('(max-width:600px)');
    
    OpenDialog(){
      if(index===0){
        this.dialogref=this.dialog.open(MyComonent,{
        maxWidth:'600px'
        });
    
        Const dialogSub= this.isMobileScreen.subscribe(result=> {
        if(result.matches){
         this.dialogref.updatesize('100%','100%');
        }
        else{
         this.dialogref.updatesize('50%');
        }
    });
    
    this.dialogref.afterclosed(). subscribe (results=>{
      dialogSub.unsubcribe():
    });
   }

Spec file

       class isMobileScreen {
            Value= new subject ();
            isMobileScreen= this.value.asObservable();
            setValue(val){ // encountering an error here - cannot read property 'setvalue' of undefined
             this.value.next(val);
            }
         }
        
      //  Inside describe    
     
       describe('component', ()=>{
          ...
        Let isMobileScreen: isMobileScreen;
        Const dialogRefMock={
              afterClosed(){
                    return of(true);
               },
               updatesize(width?:string, height?: string){}
         };
         Const dialogMock={ open:()=> dialogRefMock};
    
         // Inside before each, I provided dialogMock as a provider
         beforeEach(async(() => {
          TestBed.configureTestingModule({
          declarations: [ MyComponent],
          imports: [RouterTestingModule,MatDialogModule],
          providers: [ { provide: MatDialog, useValue: dialogStub },{provide : MatDialogRef, useValue : {}, { provide: isMobileScreen, useValue: isMobileScreen }]
        })
        .compileComponents();
      }));
      beforeEach(() => {
      fixture = TestBed.createComponent(MyComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
      isMobileScreen = TestBed.get(isMobileScreen);
      });
      it('',async(()=>{
         component.Opendialog();
         isMobileScreen.setvalue(true);
         fixture.detectChanges();
         fixture.whenStable().then(()=>{
         let spy= spyOn(component.dialogref, 'updatesize').and.callThough();
            expect (spy).toHaveBeenCalled(); // encountering an error here - this.dialogref.updatesize is not a function.
                  
          });
        }));
     });

I am facing two errors:

  1. cannot read property 'setvalue' of undefined
  2. this.dialogref.updatesize is not a function.

It seems like there might be an issue with my mocking. Any help to resolve these errors would be greatly appreciated.

Answer №1

Give this a shot

    serviceProviders: [ { provide: DialogService, useValue: dialogMock },
          {provide : DialogRefService, useValue : dialogRefMock} 
    ]

Ensure that the fake function is named adjustDimensions with uppercase A

Answer №2

instead of ridiculing dialogref, try mocking either dialog or dialogservice and provide an example like the one shown below (I apologize for not following the question format, but this approach is effective). Also, don't forget to include

{ provide: DialogService, useValue: mockDialogService }
in the list of providers.

mockDialogService = {
   open:() => {
     return {
       updateSize: (params) => { return () },
       afterclosed: of({ dataSource: {dataName: 'text1' }})
     }
   }
}

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

Angular 7 Forms: Implementing Conditional "Required" Validation with Reactive Forms

Before I get into it, I won't be able to share the actual code I'm working on due to confidentiality reasons. However, I can provide a simplified version of the code... I am working with Angular 7 and Reactive Forms. In my form, I have a radio b ...

What is the best way to create a universal function that can return a promise while also passing along event

I created a specialized function that waits for an "EventEmitter" (although it's not completely accurate as I want to use it on other classes that have once but don't inherit from EventEmitter): export function waitEvent(emitter: { once: Function ...

Creating crawlable AMP versions of Angular websites

Having an Angular website where I dynamically load object properties, I am creating separate AMP sites for each of these objects. Typically, I would link to the AMP site from the canonical site. However, the issue arises because the crawler cannot find the ...

Tips for obtaining type narrowing for a function within a mixed array

In my coding adventure, I have crafted a brilliant match function. This function is designed to take a value along with an array of [case, func] pairs. The value is then compared to each case, and if a match is found, the associated func is executed with t ...

There seems to be an issue with gulp as it is not functioning properly and the version information is

Currently, I am working on a project and have made the decision to utilize gulp for watching and transpiling Typescript files. Below are the steps I followed to set everything up: All of these actions were performed within the main directory of my projec ...

Access denied: Unable to create directory '/usr/local/lib/node_modules/node-sass/build' due to EACCES error

Currently, I am attempting to launch an Angular application. After running the ng serve command, I encounter the following message: Error: Module 'node-sass' not found ...

Transform Firestore JSON data into a TypeScript array

Extracting and formatting data from Firebase for visualization purposes can be challenging after successfully working with it in HTML. I am currently dealing with a FirebaseListObservable that contains three value-types, but only one of them needs to be in ...

What is the procedure for cancelling a file upload in the FileUpload component of PrimeNG?

1. Issue Overview Looking to terminate file upload in PrimeNG's FileUpload component when certain filename patterns are detected. Using Angular 6.0.7 and PrimeNG 6.0.2. 2. Initial Strategy 2.1. HTML Code <p-fileUpload #fileUploader name="file" ...

Angular2: Ensuring Sequential Execution Line by Line - A Comprehensive Guide

I have a designed an Angular2 Navbar Component that features a logout button: import { Component, OnInit } from '@angular/core'; import { LoginService } from '../login.service'; import { Router } from '@angular/router'; @Co ...

Setting up a Typescript project with a shared package configuration

Before I begin, there are a few premises to consider: I require a shared package that will be included in three other packages, TypeScript, Only one node modules, Ability for multiplatform usage (Windows / Linux), To utilize dependencies from the shared ...

Can Typegoose classes be used as types?

Currently, I am working on integrating my client class with a typegoose model named Member. Although I know how to use it, I am facing difficulties in setting up the types and intellisense correctly. The class is exported as MemberClass, and I need assista ...

Issue with the MUI Autocomplete display in my form

Recently, I started using Material UI and Tailwind CSS for my project. However, I encountered an issue with the Autocomplete component where the input overlaps with the following DatePicker when there is multiple data in the Autocomplete. I have attached a ...

Creating a search functionality in Angular that allows users to input multiple search terms and

I am currently delving into the world of Angular in combination with an API, and I have managed to set up a search box for querying data. However, I am facing a challenge where I cannot perform multiple searches successfully. Even though I can initially se ...

What is the best way to bring in an array from a local file for utilization in a Vue 3 TypeScript project?

Encountering a TS7016 error 'Could not find a declaration file for module '../composables/httpResponses'. '/Users/username/project/src/composables/httpResponses.js' implicitly has an 'any' type.' while attempting to ...

Angular, Observable, and the wonders of debounceTime

I have a function within an Angular 4 project called reload() that can be triggered by other functions, A() and B(), at any given time. I am looking to implement a debounce feature for reload() so that it is only executed after a specified duration (X mill ...

Checkmarking Options for Multiple Selection in P-Tables [PrimeNG]

I am struggling with implementing "Multiple selection (click + shift)" on checkboxes and cannot figure out how to make it work. The documentation provides an example called "Checkbox Selection" with a note that says, "Multiple selection can also be handle ...

The issue with Angular 2's Ng style is that it does not properly remove the old style when there is a change

I am currently experiencing an issue within my project. When assigning an object to ngStyle in a div, the problem arises where ngStyle does not clear the style properties from the previous object when there is a change in the object. It should ideally rem ...

Arrange a collection of objects by two criteria: the end time, followed by the status in accordance with the specified array order if the end times are equal

Is this the best method to arrange data by using infinity? I gave it a try but it doesn't quite meet my requirements. data = [{ "status": "Accepted", "endTime": "" }, { "status": "New", ...

Troubleshooting: Issues with accessing Angular/Typescript Class Getter property

I have a class defined as follows: export class Story { id: number; title: string; storyText: string; utcDate: string; get displayDate(): string { const today = new Date(); const postDate = new Date(this.utcDate); ...

Executing methods sequentially in the ngOnInit lifecycle hook consecutively

Working with Angular15 has presented me with a challenge. In my app.component.ts file, I have two methods: “ngOnInit()”, as shown below. public ngOnInit(): void { this.getToken(); this.UserLoggedIn(); } I am looking to run the above two functions in ...