Updating input html field from within an Angular 2 test

前端 未结 3 456
独厮守ぢ
独厮守ぢ 2020-12-02 16:51

I would like to change the value of an input field from within an Angular 2 unit test.



        
3条回答
  •  半阙折子戏
    2020-12-02 17:42

    The accepted solution didn't quite work for me in Angular 2.4. The value I had set was not appearing in the (test) UI, even after detectChanges() was called.

    The way I got it to work was to set up my test as follows:

    describe('TemplateComponent', function () {
      let comp: TemplateComponent;
      let fixture: ComponentFixture;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [ FormsModule ],
          declarations: [ TemplateComponent ]
        })
        .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(TemplateComponent);
        comp = fixture.componentInstance;
      });
    
      it('should allow us to set a bound input field', fakeAsync(() => {
        setInputValue('#test2', 'Tommy');
    
        expect(comp.personName).toEqual('Tommy');
      }));
    
      // must be called from within fakeAsync due to use of tick()
      function setInputValue(selector: string, value: string) {
        fixture.detectChanges();
        tick();
    
        let input = fixture.debugElement.query(By.css(selector)).nativeElement;
        input.value = value;
        input.dispatchEvent(new Event('input'));
        tick();
      }
    });
    

    My TemplateComponent component has a property named personName in this example, which was the model property I am binding to in my template:

提交回复
热议问题