What you need to do is get the injector that has the NgForm
. It took me a while to figure it out. I thought you could just get it from the debugElement
, but it looks like you need to get it from it's child1.
let form: NgForm = fixture.debugElement.children[0].injector.get(NgForm);
The you can just get individual controls from the form group with
let emailControl = form.control.get('email');
expect(emailControl.valid).toBe(true);
Or you can just check the form for a specific error
expect(form.control.hasError('emailInvalid', ['email'])).toBe(true);
Below is a complete test
import { Component, forwardRef, Directive } from '@angular/core';
import { TestBed, getTestBed, async } from '@angular/core/testing';
import { FormsModule, NG_VALIDATORS, Validator, AbstractControl, NgForm } from '@angular/forms';
import { dispatchEvent } from '@angular/platform-browser/testing/browser_util';
import { By } from '@angular/platform-browser';
@Directive({
selector: '[ngModel][validEmail]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => EmailValidatorDirective),
multi: true
}
]
})
class EmailValidatorDirective implements Validator {
validate(c: AbstractControl): { [key: string]: any } {
if (c.value !== '[email protected]') {
return { notPeeskillet: true };
}
return null;
}
}
@Component({
template: `
<form>
<input name="email" [ngModel]="email" validEmail />
</form>
`
})
class TestComponent {
email;
}
describe('component: TestComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [TestComponent, EmailValidatorDirective]
});
});
it('should validate', async(() => {
let fixture = TestBed.createComponent(TestComponent);
let comp = fixture.componentInstance;
let debug = fixture.debugElement;
let input = debug.query(By.css('[name=email]'));
fixture.detectChanges();
fixture.whenStable().then(() => {
input.nativeElement.value = '[email protected]';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
let form: NgForm = debug.children[0].injector.get(NgForm);
let control = form.control.get('email');
expect(control.hasError('notPeeskillet')).toBe(true);
expect(form.control.valid).toEqual(false);
expect(form.control.hasError('notPeeskillet', ['email'])).toEqual(true);
input.nativeElement.value = '[email protected]';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
expect(control.hasError('notPeeskillet')).toBe(false);
expect(form.control.valid).toEqual(true);
expect(form.control.hasError('notPeeskillet', ['email'])).toEqual(false);
});
}));
});
1 - Found it in the source code tests
browser_util
has moved toimport { dispatchEvent } from '@angular/platform-browser/testing/src/browser_util';
– Owlet