Skip to content

Instantly share code, notes, and snippets.

@paynoattn
Last active September 23, 2021 10:35
Show Gist options
  • Save paynoattn/364b475f490c453c3ca5fcc60555fa28 to your computer and use it in GitHub Desktop.
Save paynoattn/364b475f490c453c3ca5fcc60555fa28 to your computer and use it in GitHub Desktop.
Angular2 FormBuilder Specs
import {
FormGroup,
Validators,
FormBuilder
} from '@angular/forms';
import { Component } from '@angular/core';
import { User } from './../../models';
import { UserService } from './../../services';
@Component({
selector: 'login',
templateUrl: '/app/login/login.html'
})
export class LoginComponent {
user: User = UserService.BlankUser;
loginForm: FormGroup;
formValid: boolean = false;
constructor(
private fb: FormBuilder,
private userSvc: UserService
) {
this.loginForm = this.fb.group({
'email': [undefined, Validators.required],
'password': [undefined, Validators.required]
});
this.loginForm.valueChanges.subscribe(() => {
this.formValid = this.loginForm.valid;
});
}
onSubmit() {
this.user = this.loginForm.value;
this.userSvc.login(this.user.email, this.user.password);
}
}
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
inject,
TestBed,
getTestBed,
async,
fakeAsync,
ComponentFixture
} from '@angular/core/testing';
import { FormBuilder } from '@angular/forms';
import {
UserServiceStub,
blankUser,
validUser,
invalidUser
} from '../../mocks';
import { LoginComponent } from './login.component';
import { UserService } from '../../services';
let comp: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
describe('Login', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LoginComponent],
providers: [
FormBuilder
],
schemas: [ NO_ERRORS_SCHEMA ]
})
.overrideComponent(LoginComponent, {
set: {
providers: [
{ provide: UserService, useClass: UserServiceStub },
]
}
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(LoginComponent);
comp = fixture.componentInstance;
});
}));
// create reusable function for a dry spec.
function updateForm(userEmail, userPassword) {
comp.loginForm.controls['email'].setValue(userEmail);
comp.loginForm.controls['password'].setValue(userPassword);
}
it('should have default props', fakeAsync(() => {
expect(comp.user).toEqual(blankUser);
}));
it('form value should update from form changes', fakeAsync(() => {
updateForm(validUser.email, validUser.password);
expect(comp.loginForm.value).toEqual(validUser);
}));
it('isValid should be false when form is invalid', fakeAsync(() => {
updateForm(invalidUser.email, invalidUser.password);
expect(comp.formValid).toBeFalsy();
}));
it('should update model on submit', fakeAsync(() => {
updateForm(validUser.email, validUser.password);
comp.onSubmit();
expect(comp.user).toEqual(validUser);
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment