When an input event is dispatched in a unit test, the value changes of a form are not activated

Currently, I am testing a scenario where I need to verify if a value changes on the form when input is typed in.

This particular project utilizes Nrwl nx as well as jest for testing purposes.

The component code snippet is as follows:

export class InputNumericComponent implements OnInit, OnDestroy {

  @Input() form: FormGroup;

  @Input() controlName: string; 

  private _changeSubscription: Subscription;

 private get _control(): AbstractControl | null {
    return this.form?.get(this.controlName);
  }

  public ngOnInit(): void {
    if (!this._control) {
       return;
    }
    console.log('init called'); // ok
    this._changeSubscription = this._control.valueChanges
      .pipe(tap((newValue) => this._handleChange(newValue)))
      .subscribe();
  }

  public ngOnDestroy(): void {
    if (this._changeSubscription) {
      this._changeSubscription.unsubscribe();
    }
  }

  private _handleChange(value: string): void {
    console.log('_handleChange'); // never called
  }

  public handleBlur(): void {
    console.log('handleBlur'); // can be called by using dispatchEvent(new Event('blur'));
  }
}

The testing file content is as below:

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

  configureTestSuite(() => {
    TestBed.configureTestingModule({
      declarations: [InputNumericComponent],
      schemas: [NO_ERRORS_SCHEMA],
    });
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(InputNumericComponent);
    component = fixture.componentInstance;
    component.controlName = 'numeric';
    component.form = new FormGroup({
      numeric: new FormControl(),
    });
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should update form', fakeAsync(() => {
    component.ngOnInit();
    const input = fixture.debugElement.query(By.css('input'));
    input.nativeElement.value = '222';
    // i tried both and others like keydown, keypress, etc..
    input.nativeElement.dispatchEvent(new Event('change'));
    input.nativeElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    tick();
    console.log('form', component.form.get('numeric')?.value); // null
    expect(input.form.get('numeric')).toEqual('222');
  }));
});

I've encountered an issue - the input event fails to trigger the valueChanges. Even after attempting to dispatch a blur event, the handleBlur function gets executed. However, triggering the valueChanges is proving to be challenging, despite trying methods such as keydown, keypress.

On directly dispatching an input event onto the input itself, the _handleChange function does get called. It's puzzling why this didn't work as expected during testing.

Even utilizing the alternative approach of

fixture.nativeElement.querySelector('input')
yielded no results.

I'm truly unsure about what I might be missing here. Any insights or suggestions would be greatly appreciated.

Answer №1

Ensure you include ReactiveFormsModule in your TestBed imports.

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

Converting large numbers (exceeding 53 bits) into a string using JavaScript

I have a REST service that returns JSON. One of the properties in the JSON contains a very large integer, and I need to retrieve it as a string before Javascript messes it up. Is there a way to do this? I attempted to intercept every response using Angular ...

Unable to initialize the ng2-admin Angular2 Bootstrap template on a Go server due to a failed download attempt

Hello everyone, I am a newcomer to this forum and have limited experience with Angular2 and Golang. I am currently facing an issue as I want to experiment with a template on a Go server. To tackle this, I created a main.go file that includes the followin ...

Manage numerous receiving bank accounts, allowing customers to transfer money to each specific account

Managing multiple receiving bank accounts and enabling customers to transfer money to specific accounts is a key requirement in my application. Can Plaid help me achieve this functionality? Could you provide guidance on how to implement this feature using ...

Error with tsc rootDir due to Docker's installation of yarn in root directory

I am encountering a problem with my node project which serves a simple "hello world" server. Everything runs smoothly when I run it locally, but when I try to run it inside Docker, a /opt/yarn-v1.21.1 folder is created which leads to a rootDir error: erro ...

Having trouble locating the type definition file for 'cucumber' when using the Protractor framework with Cucumber and Typescript

Currently immersed in working on Protractor with Cucumber and TypeScript, encountering a persistent issue. How can the following error be resolved: Cannot locate the type definition file for 'cucumber'. The file exists within the pr ...

How can I verify the value of a class variable in TypeScript by using a method?

I need a more concise method to inform TypeScript that my client has been initialized (no longer null). While I have achieved this functionality, the current implementation seems unnecessarily verbose. Here is how it currently looks: export abstract class ...

I am looking to have the datepicker automatically clear when the reset button is clicked

this code snippet is from my component.ts file resetFilters() { this.date = 0; this.query.startedAt= null; this.query.endedAt=null; this.searchTerm = ''; this.route.params.subscribe((params) => { this.machineId = Numb ...

Strange data being received by Angular from ASP.NET API

I'm encountering some trouble with my ASP.NET API communicating with Angular, and I'm unsure of the root cause. I'm seeking assistance in reviewing my code for any glaring errors. Here is a snippet from my API Controller: // Data Structure ...

Error: Trying to access the `push` property of an undefined value is causing an issue

Issues with using the push method in TypeScript have arisen. Here are the details: Below is the code snippet for the reservation modal component: guestArray=[1, 2, 3, 4, 5, 6]; guests: number; isDateTime: boolean = false; constructor(private params: Mo ...

The specified property cannot be found within the type 'JSX.IntrinsicElements'. TS2339

Out of the blue, my TypeScript is throwing an error every time I attempt to use header tags in my TSX files. The error message reads: Property 'h1' does not exist on type 'JSX.IntrinsicElements'. TS2339 It seems to accept all other ta ...

There is a lack of a service available for AngularFireDatabase

Currently, I am trying to follow a tutorial on creating a chat room application in Angular. Unfortunately, I encountered some issues while setting up AngularFire2. Upon inspecting the package.json file, I noticed that the tutorial is using version 4.0.0-r ...

What is the best way to style an Angular 2 link with a blue color and underline effect?

In my template, I have the following code: <a (click)="delete(book)">Delete</a> Although the link functions properly, it doesn't seem visually appealing. I don't necessarily want it to be blue and underlined, but I'm unsure of ...

Error: The specified type definition file for '__mocks__' could not be located

I encountered this error upon transitioning to yarn workspaces and turbo for my collection of nextjs projects. Although it appears to be associated with jest, none of my package.json files contain jest. I have a hunch that it might be linked to a sub-depen ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

Implement Php gettext functionality in Typescript

I have a keen interest in AngularJs 2, and I am planning to incorporate it into my upcoming project. I would like to integrate i18n with Php gettext. In a previous project, I utilized Php gettext by embedding Php within Javascript code as shown below: // ...

ESLint is unable to locate the OnInit function within the "@angular/core" module

There seems to be an error: import { Component, OnInit, Input, ViewChild, ElementRef } from "@angular/core"; OnInit not found in '@angular/core'eslintimport/named The code appears to be functioning correctly, so perhaps there is a m ...

Switching buttons with AngularJS

I am currently working on a Github search app using the Github API in Angular. My goal is to make it so that when the user clicks the "Add to Favorite" button, the button disappears and the "Remove Favorite" button is displayed instead. I attempted to achi ...

The interfaced JSON object did not return any defined value

I am working on implementing a pipe in Angular 9 that will handle the translation of my table words into different languages. To achieve this, I have set up a JSON file with key-value pairs for translation services and created corresponding interfaces for ...

How do I add a new item to an object using Ionic 2?

example item: this.advData = { 'title': this.addAdvS2.value.title , 'breadcrumb': this.suggestData.breadcrumb, 'price': this.addAdvS2.value.price ...

employing a modal to create an interactive form in Angular

I recently started delving into Angular and I'm aiming to develop a dynamic form that can create entries in my database with fields that vary based on a dropdown selection in the modal header. I've searched for solutions but only found help for c ...