17

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?

3 Answers 3

22

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
});
});
Sign up to request clarification or add additional context in comments.

Comments

3

IS there a need to write fixture.detectChanges()?

I went through the same test without this and it ends with success. Button 1 is 'checked' by default

  const button1 = debugElement.nativeElement.querySelector(selectorBtn1);
  const button2 = debugElement.nativeElement.querySelector(selectorBtn2);
  ...
  expect(button1.checked).toBeTruthy();
  expect(button2.checked).toBeFalsy();

  button2.click();

  expect(button1.checked).toBeFalsy();
  expect(button2.checked).toBeTruthy();
  ...

Comments

1

ngModel directive is async one and requires to use asynchronous capabilities of Angular unit testing. Adding async and whenStable functions.

it('checkbox is checked if value is true', async(() => {
  component.model = true;
  fixture.detectChanges();

  fixture.whenStable().then(() => {
    const inEl = fixture.debugElement.query(By.css('#mob_Q1'));
    expect(inEl.nativeElement.checked).toBe(true);
  });
}));

Source LinkLink

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.