angular2 testing: Can't bind to 'ngModel' since it isn't a known property of 'input'

人盡茶涼 提交于 2019-12-17 17:59:25

问题


I am trying to test angular2 two-way binding for control input. Here is the error:

Can't bind to 'ngModel' since it isn't a known property of 'input'.

The app.component.html

<input id="name" type="text" [(ngModel)]="name" />
<div id="divName">{{name}}</div>

The app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'  
})
export class AppComponent implements OnInit {
  name: string;    
}

app.component.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
describe('App: Cli', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      providers:[AppService]
    });
  });

  it('divName', async(() => {
    let fixture = TestBed.createComponent(AppComponent);
    let comp = fixture.componentInstance;
    comp.name = 'test';
    fixture.detectChanges();

    let compiled = fixture.debugElement.nativeElement;    
    expect(compiled.querySelector('divName').textContent).toContain('test');
  }));  
});

回答1:


You need to import the FormsModule into the TestBed configfuration.

import { FormsModule } from '@angular/forms';

TestBed.configureTestingModule({
  imports: [ FormsModule ],
  declarations: [
    AppComponent
  ],
  providers:[AppService]
});

What you are doing with the TestBed is configuring a NgModule from scratch for the test environment. This allows you to only add what is needed for the test without having unnecessary outside variables that may affect the test.



来源:https://stackoverflow.com/questions/39584534/angular2-testing-cant-bind-to-ngmodel-since-it-isnt-a-known-property-of-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!