无法绑定到'(ngModel'因为它不是角度单位测试用例

时间:2017-11-23 10:03:04

标签: javascript angular unit-testing

我得到了"无法绑定到'(ngModel'因为它不是'输入的已知属性'"角度错误单元测试用例

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应更新模型值FAILED         错误:模板解析错误:         无法绑定到&#39;(ngModel&#39;因为它不是&#39;输入&#39;的已知属性。(&#34;                         ] [(ngModel] =&#34; modelValue&#34; /&GT;                        &#34)

我已导入FormsModule。如果我错过任何事情,请指导我

1 个答案:

答案 0 :(得分:3)

您的模板错误

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

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