当前位置: 首页 > 知识库问答 >
问题:

无法绑定到'(NgModel',因为它不是angular单元测试用例中'input'的已知属性

朱刚捷
2023-03-14
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');
        });
    }));
});

TestFormComponent应该更新模型值失败错误:模板分析错误:无法绑定到'(NgModel',因为它不是'input'的已知属性。(“][(NgModel]=”ModelValue“/>”)

我已经进口了FormsModule。如果我错过了什么,请指导我

共有1个答案

云航
2023-03-14

你的模板错了

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

 <input type="text" name="name" [(ngModel)]="modelValue"/>
 类似资料: