I'm trying to test a simple form using template-driven forms in Angular 9. I insert values into the inputs and click on a submit button, which sends the values to a service. The code works, but the test fails because the values always remain undefined.
I've created a demo of the problem to show here (my actual code would be too complex):
app.component.ts
@Component({
selector: 'app-root',
template: `
<form #f="ngForm" (ngSubmit)="submit(f)">
<input type="text" ngModel name="field1">
<input type="text" [(ngModel)]="field2" name="field2">
<input type="submit" value="submit">
<br>field1:
<br>submitedText:
<br>field2:
</form>
`
})
export class AppComponent {
public submitedText: string;
public field2: string;
public submit(form: NgForm) {
this.submitedText = form.value.field1;
}
}
app.component.spec.ts
describe('AppComponent', () => {
it('shoud to submit the text', () => {
const fixture = TestBed.configureTestingModule({
declarations: [ AppComponent ],
imports: [ FormsModule ],
}).createComponent(AppComponent)
fixture.detectChanges();
const field1 = fixture.elementRef.nativeElement.querySelector('input[name="field1"]');
const field2 = fixture.elementRef.nativeElement.querySelector('input[name="field2"]');
const button = fixture.elementRef.nativeElement.querySelector('input[type="submit"]');
field1.value = 'test 1';
field2.value = 'test 2';
field1.dispatchEvent(new Event('input'));
field2.dispatchEvent(new Event('input'));
fixture.detectChanges();
button.click();
fixture.detectChanges();
expect(fixture.componentInstance.submitedText).toBe('test 1');
expect(fixture.componentInstance.field2).toBe('test 2');
});
});
The result is:
Failures
AppComponent > shoud to submit the text
Expected undefined to be 'test 1'.
Expected undefined to be 'test 2'.
Could someone help me to make the inputs are correctly filled out by the test? Thanks!
Aucun commentaire:
Enregistrer un commentaire