gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:45:25 27 4
gpt4 key购买 nike

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

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

app.component.html

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

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

最佳答案

您需要将 FormsModule 导入到 TestBed 配置中。

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

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

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

关于testing - angular2 测试 : Can't bind to 'ngModel' since it isn't a known property of 'input' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com