How to write unit test case for Angular 2 Reactive forms by using Karma/Jasmine?

10,468

Solution 1

Test case to check if button is disabled or not

it('form should be invalid', async(() => {
    component.authForm.controls['userid'].setValue('');
    component.authForm.controls['password'].setValue('');
    expect(component.authForm.valid).toBeFalsy();

    // update view, once the values are entered
    fixture.detectChanges();
    let btn = fixture.debugElement.query(By.css('carbon-button'));  // fetch button element
    expect(btn.nativeElement.disabled).toBeTruthy();  // check if it is disabled
}));

Solution 2

Test case for form validation.

component:

public buildFrom() {
   this.loginForm = this.fb.group({
      'email': [undefined, Validators.required],
      'password': [undefined, Validators.required]
   });
}

Test Case:

function setFormValues(fromData) {
 component.loginFrom.control['email].setValue(fromData.email);
 component.loginFrom.control['password].setValue(fromData.password);
}

it('should have form valid", () => {
 component.buildFrom();
 const data = {
   email: '[email protected]',
   password: 'xyz'
 };
 setFormValues(data);
 expect(component.loginFrom.valid).toBeTruthy();
})


it('should have password', ()=> {
 component.buildFrom();
 const data = {
   email: '[email protected]',
   password: 'abc'
 };
 setFormValues(data);
 expect(component.loginFrom.get('password').value.length).toBeGreaterThan(0);
})
Share:
10,468
Roy
Author by

Roy

Updated on June 06, 2022

Comments

  • Roy
    Roy almost 2 years

    I have develop a simple reactive form in Angular 2, Which includes username, password and login buttons. Here button default disable up to getting email and password values. Here i am trying to write a test case for button enable by using karma/Jasmine, But i am new to this testing framework, I have written normal valid and invalid things,but not getting clarity to write this particular thing. If any one aware of this, could you please help me to quick start.

    This is my reactive form:

    <nb-card *ngIf="!loading" >
        <nb-card-header>
            <i class="fa fa-lock"></i>Sign In Form </nb-card-header>
        <nb-card-body>
            <form [formGroup]="authForm" (ngSubmit)="onLogin()" >
                <input id="userid" type="text" class="bx--text-input" placeholder="EOSE Userid" 
                formControlName="userid" [attr.data-invalid]="useridMessage ? '' : null"/> 
                
                <div class="bx--form-requirement" *ngIf="useridMessage">{{ useridMessage }} </div>	
                  <br>
                <input id="password" type="password" class="bx--text-input" placeholder="EOSE Password" 
                formControlName="password" [attr.data-invalid]="passwordMessage ? '' : null"/> 
                <div class="bx--form-requirement" *ngIf="passwordMessage" >{{ passwordMessage }} </div>
                
               <br>
                <carbon-button type="primary" [disabled]="!authForm.valid">Sign In</carbon-button>  
            </form> 
        </nb-card-body>  
    </nb-card>

    This is my .spec file.

    beforeEach(() => {
        fixture = TestBed.createComponent(LoginFormComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create the app', async(() => {
        const fixture = TestBed.createComponent(LoginFormComponent);
        const app = fixture.debugElement.componentInstance;
        expect(app).toBeTruthy();
      }));
      it('form should be invalid', async(() => {
        component.authForm.controls['userid'].setValue('');
        component.authForm.controls['password'].setValue('');
        expect(component.authForm.valid).toBeFalsy();
      }));

  • Roy
    Roy almost 6 years
    Thanks for your answer, Which you have written this test case should be pass right because button will be disable state. But this is failing with the error is"Expected undefined to be truthy."