我试图测试angular2双向绑定的control input.以下是错误:

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

应用程序.组成部分html

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

应用程序.组成部分ts

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

应用程序.组成部分规格

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配置.

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

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

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

Angular相关问答推荐

当通过指令合成添加到组件时,Angular 指令@ Investment被忽略

组合两个输入就是一个日期对象

我使用最新的AuthGuard方法,应该使用路由重定向.UrlTree如果用户未登录但未能登录

Angular material 输入字段中的图标未显示

Angular 17:在MouseOver事件上 Select 子组件的正确ElementRef

AOS-如何在向上滚动时不再次隐藏元素

Angular 应用程序未在Azure应用程序服务中运行

为什么动画只触发一次?

如果我只在组件中使用某个主题,是否需要取消订阅该主题?

如何修复不允许的HttpErrorResponse 405?

RxJS如何按顺序进行POST请求,只有在前一个完成后才会触发新的请求?

Angular 不使用NgRx的简单CRUD应用程序

ngrx 效果等到从初始值以外的其他状态收到响应

无法使用@ngrx/component-store 在其他组件中获取状态更改值

Angular 13 Sass 模块无法在编译中正确导入文件

在ionic 5中获取url传递的参数

使用 Jasmine 和 Karma 对 Angular 进行单元测试,错误:无法绑定到xxx,因为它不是xxxxxx的已知属性.

在同一个组件中使用 MatSort 的多个 mat-table

无法从模块it was neither declared nor imported导出服务

Angular 2中基于Condition条件的点击事件