Test your unit by providing feedback to the personalized modal pop-up

Currently, I am working on a unit test within Angular where I need to evaluate the functionality of the save button. My goal is to have the 'save' option automatically selected when the user clicks on the button, and then proceed to execute the subsequent lines of code.

beforeEach(async () => {

    fixture = TestBed.createComponent(component);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component.isPrivate = true;
    component.qtsval= 7.0;
    component.changeval= "";
    await component.save();
    //let ConfirmationDialogService = fixture.debugElement.injector.get(ConfirmationDialogComponent);
    spyOn(window,'confirm').and.returnValue(true);
    var displayValuationChangeDriverWarning = component.displayValuationChangeDriverWarning;
    expect(displayValuationChangeDriverWarning).toBeTruthy();
    component.isPrivate = true;
    component.qtsval= 4.0;
  });

I tried using "spyOn(window,'confirm').and.returnValue(true);" but unfortunately, it did not solve my issue. Any suggestions on how to address this problem would be greatly appreciated.

The popup window I am dealing with looks like this:

this.confirmationDialogService
      .confirm(
        this._messageService.areYouSure,
        this._messageService.wouldYouSave,
        this._messageService.save,
        this._messageService.cancel,
        true,
        false
      )
      .then(async confirmed => {});

Answer №1

Hey there, I've got a solution ready for you to check out. The main focus is on separating presentation testing from business logic. By verifying the contracts between components/providers, I ensure that the correct methods are being called internally.

This approach is applied to all relevant components specifically targeting the logic behind buttons.

During end-to-end testing, I confirm that the modal appears and the buttons are visible. While it's important to also verify that the modal disappears and the buttons become disabled, I haven't included those examples here.

This practice of separating concerns helps keep logic distinct from the UI. In my opinion, unit tests should focus solely on logic while e2e tests can target the UI components (ensuring that actions trigger the intended processes).

Enough talk, let's dive into some code examples. Below are snippets for both unit and e2e testing situations:

  it('.reject() should call activeModal with false', async () => {
    spyOn(activeModal, 'close').and.returnValue(null);

    expect(component.decline()).toBeUndefined();

    expect(activeModal.close).toHaveBeenCalledTimes(1);
    expect(activeModal.close).toHaveBeenCalledWith(false);
  });
  it('should return the correct result of a Modal (object is correct, calls internal modal)', async () => {
    const mock = {
      componentInstance: {
        title: 'Are you sure?',
        message: 'Are you actually sure though?',
        btnOkText: 'OK',
        btnCancelText: 'Cancel',
      },
      result: true,
    };

    spyOn(modal, 'open').and.returnValue(mock as any);

    const result = await service.confirm(
      mock.componentInstance.title,
      mock.componentInstance.message
    );

    expect(result).toBe(mock.result);

    expect(modal.open).toHaveBeenCalledTimes(1);
    expect(modal.open).toHaveBeenCalledWith(ModalComponent, { size: 'sm' });
  });
  it('should have an Open button on the home page, the button should open a modal with an OK option (returning TRUE)', async () => {
    page.navigateTo();

    const button = await page.getButton();
    expect(button.getText()).toBe('Open');
    await button.click();

    const modal = await page.getConfirmationModal();
    expect(await modal.isEnabled()).toBeTruthy();

    const acceptBtn = await page.getAcceptButton();

    expect(await acceptBtn.isDisplayed()).toBeTruthy();
    expect(await acceptBtn.isEnabled()).toBeTruthy();
    expect(await acceptBtn.getText()).toBe('OK');
    await acceptBtn.click();
  });

This testing method may not be perfect, but technology isn't always about right or wrong approaches. If you have suggestions for improvement or need clarification, feel free to reach out!

Visit this GitHub link for more details and examples.

I hope this information helps address your concerns. Let me know if there's anything else I can assist with!

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

Creating a JSON object from two arrays is a simple process

Consider the following two arrays: let values = ["52", "71", "3", "45", "20", "12", "634", "21"]; let names = ["apple", "orange", "strawberry", &q ...

Troubleshooting the issue of process.nextTick not being recognized in Calgolia places.js

After successfully implementing Algolia's places.js in my Angular 7 project using NPM, I encountered an issue. I have integrated a form where one of the fields should be an input. <form [formGroup]="myForm"> <pre style="color: white; b ...

Having issues with NGXS subscription not functioning properly when selecting a variable

Currently, I am working with Angular 11 and NGXS. One issue I am facing involves a subscription for a variable in the state. Here is the problematic subscription: @Select(state => state.alert.alerts) alerts$: Observable<any[]> ngOnInit(): void { t ...

Debugging with Typescript in Visual Studio Code

I attempted to use the solution found here: how to debug typescript files in visual studio code However, when I set a breakpoint in my .ts files, the debugger indicates that the file is not found. Oddly enough, breakpoints in the .js files are working fin ...

What is the best way to shift focus to the next input field once the character limit has been reached, especially when the input is contained

My challenge lies in having six input fields arranged side by side in a single row: In my component.html file: onDigitInput(event: any) { let element; if (event.code !== 'Backspace') element = event.srcElement.nextElementSibling; consol ...

Implementing a new field in a Node.js model using MongoDB

In my Node.js API, I have a user model working with MongoDB and Angular as the front-end framework. I decided to add a new field named "municipalityDateChange" to my user model. After doing so, I attempted to send an HTTP request from Angular to the Node A ...

Is it possible to utilize a React component within the DataGrid cell instead of the standard cell types like 'string', 'number', 'date', and 'dateTime' in Material UI?

Using React, Material UI, and TypeScript I am trying to embed a React component into the cell of a DataGrid but have encountered an issue. I have explored custom column types for cells here, however, it only allows me to manage string formats, whereas I ...

Confounding Typescript Type Bindings

I am facing an issue with my Typescript component that uses react-jss and the classes object for styling. The error message I'm getting is: Binding element 'classes' implicitly has an 'any' type., and I'm struggling to find a ...

Step-by-step guide on invoking an asynchronous method in canActivate for Ionic and Angular

My objective is to acquire a token for authenticating users. I am utilizing the import { Storage } from '@ionic/storage-angular'; to store the data, but I am encountering an issue where the Storage methods only function in asynchronous mode. Her ...

Idea fails to detect imports

I have been attempting to use Angular2 in IntelliJ IDEA IDE. Although my code is valid (I have tried compiling and executing it), the IDE keeps showing me this error: https://i.stack.imgur.com/w6wIj.jpg Is there a way to configure IntelliJ IDEA to hide t ...

Issue with NextJS Image Optimization in Vercel's production environment

As of now, I am developing a NextJS application that will eventually be deployed with multiple domains on Vercel. One of the key features of my application is the dynamic rendering of images. While all images display correctly in the preview environment on ...

Exploring Typescript and Clean Architecture with an In-Memory Database/Repository

Currently, I am integrating clean architecture in my latest project and facing challenges with repositories, data sources, and terminology. My aim is to test my useCases using an in-memory repository as I am only concerned about the business logic at this ...

What is the best way to reproduce the appearance of a div from a web page when printing using typescript in Angular 4?

Whenever I try to print a div from the webpage, the elements of the div end up on the side of the print tab instead. How can I fix this issue? Below is my current print function: print(): void { let printContents, popupWin; printContents = document.getEl ...

Using typescript for Gnome shell extension development. Guidelines on importing .ts files

I'm currently working on a gnome shell extension using typescript, but I've encountered issues when trying to import .ts files. The Gnome shell documentation suggests configuring the tsconfig file as outlined in this Gnome typescript docs: { &q ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

Sveltekit: Troubleshooting problem of refreshing when utilizing store and localStorage

I am currently working on persisting data using localStorage and have successfully achieved persistence. However, I notice that when I refresh the page, it initially displays a value of 0 before fetching the localStorage value. Is there a way for me to ins ...

Error encountered when dispatching action in ngOnInit: ExpressionChangedAfterItHasBeenCheckedError

I have set up my AppComponent to subscribe to the ngrx store in its constructor: export class AppComponent { submenuItems: Observable<Array<INavigationBarItem>>; constructor(private store: Store<AppState>) { this.submenu ...

Include a new module in the declarations NgModule utilizing ts-morph

Currently, I am utilizing the ts-morph library and my objective is to add a new component to the declarations: This is my initial setup: @NgModule({ declarations: [], imports: [], providers: [], }) Here is what I am aiming for: @NgModule({ declarations: [ ...

Transforming an ordinary JavaScript object into a class instance

As I was delving into Angular's documentation on "Interacting with backend services using HTTP", I came across the following statement in the "Requesting a typed response" section: ...because the response is a plain object that cannot be automatical ...

Tips for adding a new property to an array object in TypeScript using a condition

Here is an array object that I have: arr = [ { Name: "ABC", Age: 20}, { Name: "XXX", Age: 15} ]; In Typescript, I am looking to dynamically add a new property called "Flag" with a value of 1 only if the Age is greater than 15. Can someone suggest ...