简体   繁体   中英

Can't bind to '(ngModel' since it isn't a known property of 'input' in angular unit test case

I got "Can't bind to '(ngModel' since it isn't a known property of 'input'" error in angular unit test case

import { Component } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';

@Component({
    template: `<form>
                <input type="text" name="name" [(ngModel]="modelValue"/>
               </form>`
})

class TestFormComponent {
    modelValue: 'xyz';
}

describe('TestFormComponent', () => {
    let component: TestFormComponent;
    let fixture: ComponentFixture<TestFormComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ FormsModule ],
            declarations: [ TestFormComponent ]
        }).compileComponents();
        fixture = TestBed.createComponent(TestFormComponent);
        component = fixture.componentInstance;
    });

    it('should be ok', async(() => {
        fixture.detectChanges();
        fixture.whenStable().then(() => {
            const input = fixture.debugElement.query(By.css('input'));
            const el = input.nativeElement;

            expect(el.value).toBe('xyz');

            el.value = 'abc';
            el.dispatchEvent(new Event('input'));

            expect(component.modelValue).toBe('abc');
        });
    }));
});

Error

TestFormComponent should update model value FAILED Error: Template parse errors: Can't bind to '(ngModel' since it isn't a known property of 'input'. (" ][(ngModel]="modelValue"/> ")

I have imported FormsModule. Please guide me if anything i missed out

Your template is wrong

change from

 <input type="text" name="name" [(ngModel]="modelValue"/>

to

 <input type="text" name="name" [(ngModel)]="modelValue"/>

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