简体   繁体   中英

NgModel not Updating for Input of Type Radio in Angular Testing

I have the following input in my Angular 2 application:

<input 
    id="radio-{{geo.id}}"
    name="radio-geos"
    type="radio" 
    [value]="geo.value"
    [(ngModel)]="selectedGeo">

The selectedGeo is bound to public selectedGeo: string;

I'm writing the following for my input element:

it('should select the US Home Region', (done) => {
        // Arrange
        const component = TestBed.createComponent(regionComponent);

        // Act
        component.detectChanges();
        const usGeoRadioButton = component.debugElement.query(By.css('#radio-0'));                

        usGeoRadioButton.triggerEventHandler('click', null);
        component.detectChanges();
        const selectedGeo = component.componentInstance.selectedGeo;

        // Assert
        component.whenStable().then(() => {
            expect(selectedGeo).toBe('US');
            done();
        });
    });

After running the tests in Karma, I notice that the radio button is not being clicked on and the selectedGeo is not being updated. My test fails because selectedGeo comes back as undefined.

I'm not sure why this is happening and I've done some research on dispatchEvent and how the [(ngModel)] is updated but I haven't been able to figure this out.

Any suggestions?

Shouldn't your input tag be formatted like this (with no brackets around value and ng-model):

<input type="radio" ng-model="string" value="string" [name="string"]...>

Doc link: https://docs.angularjs.org/api/ng/input/input%5Bradio%5D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM