I hope this question clarifies so many people about testing template driven forms that Angular documentation barely mentions. I have an input inside this form that I want to test. I want to test a simple DOM in Angular using Jasmine. This is a template driven form using NgForm like this:
<form name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm">
<input #inputtotest type="text" class="form-control" name="nombre" id="field_nombre"
[(ngModel)]="paciente.nombre" required/>
I want to test only:
- If this input for this label sends data (paciente.nombre) using NgModel or better if its Property is paciente.model.
According to this responses we can use ViewChild
for that: use of viewchild on DOM How to get ngForm variable reference in the component class
My component file is like this:
//all the other imports
import { ViewChild } from '@angular/core';
@Component({
...
})
export class PacienteDialogComponent implements OnInit
{
@ViewChild('inputtotest') inputtotest: **ElementRef**; //Create a viewchild of my input s I can obtain its value
paciente: Paciente; //Paciente is a modal that initializes the nombre
...
}
And my spec file to write the tests for the form is like this:
//All te Angular imports
describe('Component Tests', () => {
describe('Paciente Management Dialog Component', () => {
let comp: PacienteDialogComponent;
let fixture: ComponentFixture<PacienteDialogComponent>;
//starts my code
let input: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
.....angular imports
}));
beforeEach(() => {
fixture = TestBed.createComponent(PacienteDialogComponent);
comp = fixture.componentInstance;
input = `fixture.debugElement.query(By.css('inputtotest')).nativeElement;`
});
Tests:
it ('The form should call save method on submit', async(() => {
fixture.detectChanges();
spyOn(comp,'save');
savebutton.click();
expect(comp.save).toHaveBeenCalledTimes(0);
}));
it ('The form should have the input for paciente.nombre', async(() => {
fixture.detectChanges();
expect(inputname.getAttribute.value).toEqual(paciente.nombre);
}));
Now I have obtained the input as a HTMLelement and I do not find any way on how to check that it is Equal to ngModel value that is paciente.nombre. I do it like in the example and the result is the error:
Property value does not exist in type name string. Have I done something wrong?
By.css()
you should use a classname, likeBy.css('.inputtotest')
and<input #inputtotest class="inputtotest".../>
– Boadicea