A guide to simulating Custom Dialog in Angular for Unit Testing with Jest

Currently, I am in the process of creating test cases for unit tests and ensuring code coverage for a method that triggers a dialog component when isEdit = 'true' which is retrieved from localStorage.

The issue arises with the first test case where I am setting isEdit = true and invoking the method showMessagesList(). The lines within the if statement are covered in code coverage but the test case fails with an exception stating

Cannot read property 'openModalDialog' of undefined
. However, the second test case does not fail because it is being Spied On. I need assistance in mocking the Dialog component in Jest to resolve this error.

Error Message SideBarDrawerComponent › should call show Message Items when true

    TypeError: Cannot read property 'openModalDialog' of undefined

      49 |     this.isEdit = localStorage.getItem('isEditMode').toString()
      50 |     if (this.isEdit === 'true') {
    > 51 |       this.modalDialog.openModalDialog()
         |                                ^
      52 |     } else {
      53 |       this.toggleComponent.emit(componentTypes.LIST)
      54 |     }

Method in Component

showMessagesList() {
    // Check if the compose componenet is in edit mode;
    this.isEdit = localStorage.getItem('isEdit').toString()
    if (this.isEdit === 'true') {
      this.modalDialog.openModalDialog() // exception when isEdit is set to 'true' in the test case
    } else {
      this.toggleComponent.emit("true")
    }
  }

Spect.ts file

import { ComponentFixture, TestBed } from '@angular/core/testing'
import { By } from '@angular/platform-browser'
import {
  ModalDialogComponent,
  ModalDialogModule,
} from 'modal-dialog'

import { ContentModel } from '../../model/content.model'
import * as componentTypes from '../componentTypes'
import { ComposeComponent } from '../compose-message/compose.component'
import { MessageItemsComponent } from '../message-list/message-item.component'
import { SideBarDrawerComponent } from './side-bar-drawer.component'
import spyOn = jest.spyOn


window.ResizeObserver =
  window.ResizeObserver ||
  jest.fn().mockImplementation(() => ({
    disconnect: jest.fn(),
    observe: jest.fn(),
    unobserve: jest.fn(),
  }))

describe('SideBarDrawerComponent ', () => {
  let component: SideBarDrawerComponent 
  let fixture: ComponentFixture<SideBarDrawerComponent>

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [ModalDialogModule],
      declarations: [
        SideBarDrawerComponent,
        MessageItemsComponent ,
        ComposeComponent,
        ModalDialogComponent, // <-- Dialog Component
      ],
      providers: [
        { provide: Window, useValue: window },
        { provide: ModalDialogComponent, useValue: {} },
      ],
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(SideBarDrawerComponent)
        component = fixture.componentInstance
      })
  })

  beforeEach(() => {
    component.content = mockContent
  })

  it('should call show Message Items when true', () => {
    localStorage.setItem('isEditMode', 'true')
    component.showMessagesList()
    component.isEdit = localStorage.getItem('isEditMode') ?? ''
    fixture.detectChanges()
    expect(component.isEdit).toBe('true')
  })

  it('should check open dialog', () => {
    const isEdit = 'true'
    component.isEdit = isEdit.toString()
    expect(component.isEdit).toBe('true')
    jest.spyOn(component, 'showMessagesList').mockImplementationOnce(() => {
      if (isEdit === 'true') {
        expect(component.modalDialog.openModalDialog).toBeCalled()
      }
    })
  })
})

Answer №1

There seems to be a potential typo issue, as I have identified an error in this code snippet:

this.exampleModalDialog4.openModalDialog()
// --------------------^-----4 added here.

To address this issue, you can consider providing some mock method implementations for the Modal dialog component:

{ 
  provide: ModalDialogComponent, 
  useValue: {
     openModalDialog: () => {},
     // other implementations
  } 
},

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

Steps for passing a JSON object as a PathVariable in a Spring controller

Currently, I am in the process of developing a spring application using AngularJS. My goal is to pass a JSON object as a @PathVariable to the spring controller. However, with my existing code, I am facing an issue where when attempting to pass the JSON obj ...

When in production mode, parameter routing and conditions do not function as expected

I have a straightforward routing setup like the following: import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: 'scenario', ...

Testing an event within a subscription in Angular 4: A step-by-step guide

I am facing an issue with my component where I subscribe to an event in the constructor. To send an event, I use an event service: import {Injectable} from '@angular/core'; import {Observable} from "rxjs/Observable"; import {Subject} from "rxjs ...

Export an array of objects using the ExcelService module

I am working with an array named listTutors that looks like this: listTutors = [{ countryId: 'tt', gender: 'both', levelId: 'tg', sessionType: 'inPerson', dashboardStatus: ['notPublished', 'p ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

TypeScript is failing to identify a correctly typed property

Currently, I am facing issues while converting a Material UI Dashboard from React to Typescript. The problem arises during TypeScript compilation where the property in question meets the criteria mentioned in the error message. To put it briefly, the compi ...

Discovering Child Elements in Angular 2 with @ViewChild and CSS Selectors

I'm looking to update the style of the second paragraph using either the nth-child() selector or by a specific class: import { Component, ViewChild } from '@angular/core'; @Component({ selector: 'my-app', template: ` <d ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Sharing information between sibling modules

Currently, I am faced with the challenge of transmitting data between two sibling components within the following component structure. The goal is to pass data without changing the relationships between these components. I prefer not to alter the componen ...

If the boolean value is false, the material icon set will be colored red

My task management application requires a thumbs up/down icon to be displayed in green or red based on whether the task is completed or not. Previously, I was able to achieve this by using ngClass and applying different CSS classes to the icon. HTML: < ...

Is there a way to simultaneously call two APIs and then immediately call a third one using RXJS?

I am looking to optimize the process of making API calls by running two in parallel and then a third immediately after both have completed. I have successfully implemented parallel API calls using mergeMap and consecutive calls using concatMap, but now I w ...

Exporting from Excel is causing dates and times to be displayed as numbers instead

Having trouble with a specific date while exporting an Excel file. Refer to the screenshot of the Excel file for clarity: https://i.stack.imgur.com/7mFE4.png The date '01/02/2019 00:00:00' is being treated as a number instead of displaying corre ...

Identifying imports from a barrel file (index.ts) using code analysis

Can anyone help me understand how the Typescript compiler works? I am trying to write a script that will parse each typescript file, search for import declarations, and if an import declaration is using a barrel-file script, it should display a message. Af ...

Cannot assign an array of Typescript type Never[] to an array of objects

Creating an object array can sometimes lead to errors, let's take a look at an example: objectExample[a].push({ id: john, detail: true }); objectExample[a].push({ id: james, detail: false}); const objectExample = { a = [ { id: john, detail: true} ...

What is the best way to perform a deep copy in Angular 4 without relying on JQuery functions?

Within my application, I am working with an array of heroes which are displayed in a list using *ngFor. When a user clicks on a hero in the list, the hero is copied to a new variable and that variable is then bound to an input field using two-way binding. ...

Encountered issue: The type 'Teacher[]' cannot be assigned to the type 'Teacher'

I am currently working on enhancing my angular application by adding a new service. However, I have encountered an error that I need help fixing: The error message states: Type 'Teacher[]' is not assignable to type 'Teacher'. Property ...

Why does WebStorm fail to recognize bigint type when using TSC 3.4.x?

Currently, I am working on the models section of my application and considering switching from using number to bigint for id types. However, despite knowing that this is supported from TSC 3.2.x, WebStorm is indicating an error with Unresolved type bigint. ...

Is it possible for the filter with the new date() function to accept formats other than yyyy-mm-dd?

After receiving a response from mydatepicker in the specific format below: { "isRange":false, "singleDate":{ "date":{ "year":2022, "month":5, "day":13 }, "jsDate": ...

The guidelines for implementing pipes in Angular 2

I am struggling with writing a pipe that should filter for both AUID and firstname. Unfortunately, it seems to only be working for the firstname. Can anyone help me figure out why? Below is the code snippet in question: return value.filter((searc ...

Tips for personalizing Ion text area in Ionic?

Seeking assistance on how to effectively utilize ion-textarea. As a novice in the realm of Ionic, I am encountering various challenges while working with this feature. The issue lies in the fact that instead of displaying a scrollbar on the right side, the ...