Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test the checkbox in Angular2

I have a sample code for checkbox written with Angular2.

<div class="col-sm-7 align-left" *ngIf="Some-Condtion">
    <input type="checkbox" id="mob_Q1" value="Q1" />
    <label for="mob_Q1">Express</label>
</div>

I want to unit test the above checkbox. Like I want to recognize the checkbox and test whether it is check-able. How do I unit test this with Karma Jasmine?

like image 778
Protagonist Avatar asked Dec 29 '16 15:12

Protagonist


People also ask

How do you checked the checkbox in Angular?

AngularJS ng-checked DirectiveThe ng-checked directive sets the checked attribute of a checkbox or a radiobutton. The checkbox, or radiobutton, will be checked if the expression inside the ng-checked attribute returns true. The ng-checked directive is necessary to be able to shift the value between true and false .


1 Answers

Component, e.g. CheckboxComponent, contains input element. Unit test should looks like:

import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {CheckboxComponent} from './checkbox.component';

describe('Checkbox test.', () => {

let comp: CheckboxComponent;
let fixture: ComponentFixture<CheckboxComponent>;
let input: Element;

beforeEach(() => {
    TestBed.configureTestingModule(
        {
            declarations: [CheckboxComponent],
        },
    );

    fixture = TestBed.createComponent(CheckboxComponent);
    comp = fixture.componentInstance;
    input = fixture.debugElement.query(By.css('#mob_Q1')).nativeElement;
});

it('should click change value', () => {
    expect(input.checked).toBeFalsy(); // default state

    input.click();
    fixture.detectChanges();

    expect(input.checked).toBeTruthy(); // state after click
});
});
like image 100
EvgenyV Avatar answered Sep 21 '22 23:09

EvgenyV