dimanche 15 novembre 2020

How to test typing to an input element?

I'm trying to test 'typing' to an input element.

The code:

app.component:

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  template: `
    <span>My input: </span>
    <input name="name-input" placeholder="Enter name" [(ngModel)]="name" />
  `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "";
}

The test:

import { TestBed } from "@angular/core/testing";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";

describe("AppComponent", () => {
  var fixture: any;
  var app: AppComponent;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [FormsModule]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    app = fixture.componentInstance;
  });

  it("should create the app", () => {
    expect(app).toBeTruthy();
  });

  it("should type text into input element", () => {
    let inputElement = fixture.nativeElement.querySelector(
      `input[name='name-input']`
    );

    inputElement.value = "someValue";
    inputElement.dispatchEvent(new Event("input"));
    fixture.detectChanges();

    expect(app.name).toBe("someValue");
  });
});

A stackblitz which proves that it doesn't work: https://stackblitz.com/edit/stackoverflow-input-question1q2w3e?

Aucun commentaire:

Enregistrer un commentaire