My objective is to test the 'typing' functionality in an input element. The aim is to insert a value into the input element, verify that its binding successfully captures the value, and observe the entered value within the input element.
Below is the code snippet:
In 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 testing block:
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");
});
});
Upon executing:
inputElement.value = "someValue";
inputElement.dispatchEvent(new Event("input"));
fixture.detectChanges();
Expected Result: app.name should be equal to "someValue". Current Outcome: app.name remains an empty string: "".
You can access a StackBlitz demo illustrating this issue: https://stackblitz.com/edit/stackoverflow-input-question1q2w3e?