角度测试:FormControl的值可观察到的变化

时间:2018-08-18 16:33:04

标签: angular unit-testing jasmine karma-jasmine

我有文本输入,我在听更改。

组件

name = new FormControl('',Validators.required);

ngOnInit() {
  this.data = 'oldvalue';
  this.checkName();
}

checkName() {
  this.name.valueChanges.subscribe(val=>{
     console.log(val);
     this.data= "newvalue"; // updating Value
  });
}

HTML

<input name="name" formControlName="name">

到目前为止我的尝试:

component.spec.ts

it('should test data field ', () => {
    const fixture = TestBed.createComponent(UserComponent);
    const app=fixture.debugElement.componentInstance;
    const el = fixture.nativeElement.querySelector('input');
    el.value ='something';
    dispatchEvent(new Event(el));
    fixture.detectChanges();
    fixture.whenStable().then(()=>{expect(app.data).toBe('newvalue');
});

问题: 即使填充了输入字段,也不会执行订阅回调中的代码。

它始终显示:

  

预计“旧值”为“新值”。

我也尝试了setValue()方法,但是没有用。它永远不会进入订阅回调

app.name.setValue('vikas');
fixture.detectChanges();
fixture.whenStable().then(()=>{expect(app.data).toBe('newvalue');

我推荐了Updating input html field from within an Angular 2 test Angular2 Component: Testing form input value change,但没有运气:(

我想念什么?

1 个答案:

答案 0 :(得分:8)

乍看之下,我认为您错过了FormControl未连接到输入的事实,因为您正在使用def drive(request): user = request.user social = user.social_auth.get(provider='google-oauth2') creds=google.oauth2.credentials.Credentials(social.extra_data['access_token']) drive = googleapiclient.discovery.build('drive', 'v3', credentials=creds) files = drive.files().list().execute() 指令,该指令将控件名称命名为FormControlName

如果要测试FormControl,则可以考虑将@Input用作FormControlDirective的{​​{1}}:

FormControl

现在,我们可以确定,只要我们更改输入中的文本,您的@Input就会触发更改。但是,一旦您编写了这样的模板,Angular就会在测试中要求您提供<input name="name" [formControl]="name"> ^^^^^ `name` is FormControl instance here not string 依赖性:

FormControl

现在要进行测试。

1)您必须通过调用ReactiveFormsModule来告诉import { ReactiveFormsModule } from '@angular/forms'; .... TestBed.configureTestingModule({ imports: [ ReactiveFormsModule <=== add this ], declarations: [TestComponent], }); 执行数据绑定:

TestBed

2)您应该正确触发输入的更改:

fixture.detectChanges()

这是整个代码:

const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges(); <== add this

Plunker Example

相关问题