I have two question in regards to mocking Formbuilder in Angular2.
1) How do I mock formBuilder in a spec? Are there any given mocks that we can use? I would like to for instance, update the values of a form in my spec, and then test to see if the form is still valid - or test the functionality of methods in my component that update a formbuilder group, or determine if a formbuilder group is valid.
2) How do I deal with the following error given that fb is a DI injection of Formbuilder in a spec?
null is not an object (evaluating 'this.fb.group')
when the component is as follows:
export class LoginComponent implements OnInit {
constructor( private fb: FormBuilder ) {}
ngOnInit() {
this.loginForm = this.fb.group({
'email': this.user.email,
'password': this.user.password
});
}
}
How would you test that? Create a spec, using Angular's TestBed. Pass FormBuilder as a provider, and make sure to override any services with stubs. Then you should have full access to set the values of your form's controls, check whether the form is valid, and test other basic FormBuilder functionality.
Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. This testing methodology is done during the development process by the software developers and sometimes QA staff.
I actually build a new instance of FormBuilder and give it to component under testing.
sut = new LoginComponent(service, new FormBuilder());
If you want to modify any control that belongs to your ControlGroup/FormGroup then you can do it in following manner:
(<Control>sut.loginForm.controls['Name']).updateValue('Jon Doe');
You can test validity as well:
sut.loginForm.valid
Update:
describe('Component', () => {
let sut: Component;
let service: Service;
beforeEach(() => {
service = new Service(null);
sut = new Component(new FormBuilder(), service);
});
it('should have object initialized', () => {
expect(sut.selectedBankAccount).toBeDefined();
});
...
If you are using the newest version of Angular2, and want to use their testbed, here is a working spec.
describe('Login Component', () => {
let comp: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LoginComponent],
providers: [
FormBuilder
]
}).compileComponents()
.then(() => {
fixture = TestBed.createComponent(LoginComponent);
comp = fixture.componentInstance;
});
}));
it('user should update from form changes', fakeAsync(() => {
const testUser = {
email: '[email protected]',
password: '12345'
};
comp.loginForm.controls['email'].setValue(testUser.email);
comp.loginForm.controls['password'].setValue(testUser.password);
expect(comp.user).toEqual(testUser);
}));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With