angular2 测试:无法绑定到“ngModel",因为它不是“input"的已知属性 [英] angular2 testing: Can't bind to 'ngModel' since it isn't a known property of 'input'

查看:34
本文介绍了angular2 测试:无法绑定到“ngModel",因为它不是“input"的已知属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试控制 input 的 angular2 双向绑定.这是错误:

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'.

app.component.html

The app.component.html

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

app.component.ts

The app.component.ts

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

app.component.spec.ts

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');
  }));  
});

推荐答案

您需要将 FormsModule 导入 TestBed 配置.

You need to import the FormsModule into the TestBed configfuration.

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

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

您使用 TestBed 所做的是从头开始为测试环境配置 NgModule.这允许您只添加测试所需的内容,而无需添加可能影响测试的不必要的外部变量.

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.

这篇关于angular2 测试:无法绑定到“ngModel",因为它不是“input"的已知属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆