How to unit test the checkbox in Angular2

前端 未结 2 1596
北海茫月
北海茫月 2021-02-20 03:05

I have a sample code for checkbox written with Angular2.


    

        
相关标签:
2条回答
  • 2021-02-20 03:23

    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();
      ...
    
    0 讨论(0)
  • 2021-02-20 03:28

    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
    });
    });
    
    0 讨论(0)
提交回复
热议问题