Angular form validation error message not visible during test for invalid input

Within my Angular application, there exists a straightforward component housing a form inclusive of a text input field.

This input specifically permits strings fewer than 255 characters. In the event that a user types in a string exceeding this limit, an error message is triggered:

https://i.sstatic.net/Yi5xw.png

The following test scenario has been devised:

it('should trigger an error message when the entered description surpasses the character limit', () => {
  const inputElement: HTMLInputElement = hostElement.querySelector('.input-element');

  inputElement.value = getRandomString(256);
  inputElement.dispatchEvent(new Event('input'));
  fixture.detectChanges();

  const errorElement: HTMLElement = hostElement.querySelector('.error-element');

  expect(errorElement).toBeTruthy();
  expect(errorElement.innerText).toContain('Please enter no more than 255 characters.');
});

Despite employing fixture.detectChanges() post the input event dispatch, and even though the form control status deems as INVALID complete with an error (which I've confirmed through code debugging), the failure to show the error message during the test execution results in failing expectations.

Answer №1

The issue at hand is that the error message does not appear until the user exits the field, such as by clicking elsewhere or pressing the TAB key.

To address this, we must ensure that the inputElement triggers a blur event:

inputElement.dispatchEvent(new Event('blur'));

The updated test now reads as follows:

it('should show an error message if the entered description text exceeds the character limit', () => {
  const inputElement: HTMLInputElement = hostElement.querySelector('.input-element');

  inputElement.value = getRandomString(256);
  inputElement.dispatchEvent(new Event('input'));
  inputElement.dispatchEvent(new Event('blur')); // this line has been included
  fixture.detectChanges();

  const errorElement: HTMLElement = hostElement.querySelector('.error-element');

  expect(errorElement).toBeTruthy();
  expect(errorElement.innerText).toContain('Please enter no more than 255 characters.');
});

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

Tips for controlling the upload of a .exe.png file or converting a .exe file to a png file for uploading in angular 8

I had originally set up restrictions to only allow image file types such as JPG, JPEG, PNG, and TIFF. However, I discovered that users were able to upload .exe files simply by renaming them. For example, changing dell.exe.png or dell.exe to dell.png allo ...

"Dealing with Cross-Origin Resource Sharing Problems When Uploading Files with Angular

After recently starting to experiment with angular2, I decided to try out angular2 file upload. I followed the tutorial from here I copied the code exactly as instructed, but encountered the following issue: Upon attempting to load http://localhost:808 ...

Ways to resolve the TypeScript reference issue

I am encountering a TypeScript error in the code snippet below, even though I specified it as Record<"abc", string>? interface IFoo { key ?: | string | Record<"abc", string> | boolean | string[] } const tes ...

Ways to verify whether a checkbox is selected and store the status in the LocalStorage

Hey there, I'm still new to the world of programming and currently just a junior developer. I have a list of checkboxes and I want to save any unchecked checkbox to my local storage when it's unselected. Below is a snippet of my code but I feel l ...

A guide on logging errors triggered within reducers

I'm facing a challenge in Redux where I am unable to get error messages logged to the console. My stack includes React, Redux Toolkit, and TypeScript. Here is a snippet of one of the reducers I've implemented: // Reducer const removeResourceRedu ...

Steps for Loading HTML5 Video Element in Ionic 2

Struggling to showcase a list of videos from my server, here's the issue I'm encountering and the layout of the app. https://i.stack.imgur.com/HWVt3.png This is the code snippet in HTML: <ion-list> <button ion-item *ngFor="let v ...

JSON.stringify omits any properties in a custom class that have not been explicitly declared in the constructor

I recently defined a new class in my code: export class SavedData{ public isDone : boolean; } After trying to stringify an instance of this class, I noticed that the isDone property was not included: console.log(new SavedData()); This resulted in a ...

Managing numerous HTTP requests and providing the outcome through Angular and Rxjs

Currently, I am facing a challenge with sending GET requests for a large number of URLs (50 of them) to the Spotify server and then returning their results in a single Observable/array/object. This is the code snippet I have come up with: curatedTopArti ...

Ways to extract information from nested JSON arrays in objects?

We are currently developing an Extension for WeClapp, with Custom Attributes that can be added to various Datatypes within the platform. These Attributes are accessible through a nested JSON object Array. Here is an example of the interface: export inter ...

Utilizing Angular to Make API Requests

When attempting to call a Rest API from my Angular Front End, I am encountering a permission issue related to Access control origin. Below is the code snippet from my front end: import { Injectable } from '@angular/core'; import { Observable } ...

Tips for sending FormData along with additional variables in a single HTTP Post request (Using Angular and Node)

I need to send two different types of data to the backend: a file in a FormData object and a Book object Is there a way to combine these into one post request? The image upload feature is already functional! Thank you in advance! Front end: Angular u ...

Utilizing Object.fromEntries in Typescript

I am attempting to define a type called ObjectFromEntries that functions similarly to the return type of the Object.fromEntries function. Here is what I have so far: type ObjectFromEntries<Entries extends [keyof any, any][]> = { [key in Entries[numb ...

Error: Attempting to change a read-only property "value"

I am attempting to update the input value, but I keep receiving this error message: TypeError: "setting getter-only property "value" I have created a function in Angular to try and modify the value: modifyValue(searchCenter, centerId){ searchCenter.va ...

What is the best way to send parameters to an async validator when working with reactive controls in Angular

Issue with Validation I am facing a challenge while using the same component for both read and edit routines. The async-validator functions perfectly when dealing with new entries. However, a problem arises if the user mistakenly changes a value and then ...

The Angular 9 component remains static on the page despite successfully capturing the correct value from the URL

Below, you will find the code for my component where I have included router links to change the view when either the text or the image with the associated routerLink is clicked. However, despite the correct value being reflected in the browser URL after ea ...

What is the reason behind typescript-eslint's insistence on using camelCase for enumMember?

The TypeScript documentation showcases enum examples with PascalCase for enum members, like: this enum Direction { Up = 1, Down, Left, Right, } However, @typescript-eslint/naming-convention mandates camelCase over PascalCase, resulting in: enum Di ...

Error: It is not possible to add the "providers" property as the object is not extendable within N

Ever since updating to the latest version of NGRX, I've been encountering an issue: users$= createEffect(() => this.actions$ .pipe( ofType(users.LOAD_USERS), tap((action: users.LoadUsersAction) => { action.item.name = ...

Saving data from a one-to-one relationship using TypeORM and NestJS in a socalled way is a breeze - here's how you

When working with TYPEORM, I have a requirement to create two entities in the database: one for the user and another to store tokens. However, I face a challenge when trying to fill both entities simultaneously during the user creation process. Can someone ...

What are some ways to detect TypeScript type errors in the data of a Vue component?

Recently, I delved into Typescript development using Nuxt-ts and Vue 2. My goal was to steer clear of class-style components so I opted for the following approach. I created my Interfaces in a folder named /types. Whenever I needed to declare a type in a ...

"iOS users have reported that notifications from Firebase have mysteriously ceased to

Yesterday evening, I was experimenting with Push Notifications from Firebase on my iOS application and everything was functioning correctly. I successfully sent a notification from a Cloud Function to a specific FCM token. However, this morning, notificat ...