gpt4 book ai didi

unit-testing - Angular NgModel双向绑定(bind)单元测试

转载 作者:太空狗 更新时间:2023-10-29 17:54:40 26 4
gpt4 key购买 nike

我正在尝试测试 Angular 2 中的双向绑定(bind)功能。我还阅读了其他一些答案,但我仍然无法通过测试。

当输入字段更新时,我想运行一个测试以确保 AppComponent 类上的 searchQuery 属性与输入字段的值相同。

如前所述,我已经阅读了一些其他答案,并且随着我的阅读包括了额外的代码片段。那么目前可能不需要的是什么?

组件

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: '<input type="text" name="input" [(ngModel)]="searchQuery" (change)="onChange()" id="search">',
styles: ['']
})
export class AppComponent {
public searchQuery: string;

onChange() {
console.log(this.searchQuery);
}

}

单元测试

import { ComponentFixture, TestBed, async, fakeAsync, tick, ComponentFixtureAutoDetect } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

describe('AppComponent', () => {
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent ],
providers: [],
imports: [ FormsModule ],
schemas: []
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
});

it('should create the app', fakeAsync(() => {
const de = fixture.debugElement.query(By.css("#search"));
const el = de.nativeElement;

el.value = "My string";

var event = new Event('input', {
'bubbles': true,
'cancelable': true
});
el.dispatchEvent(event);

tick();

fixture.detectChanges();

expect(comp.searchQuery).toEqual("My string");
}));
});

如果有更好的方法,我当然很乐意就此获得任何反馈。

最佳答案

你必须跑

fixture.detectChanges();

在调度事件之前确保你的控件已经初始化并注册了onChange事件

setUpControl 函数

// view -> model
dir.valueAccessor.registerOnChange(function (newValue) {
dir.viewToModelUpdate(newValue);
control.markAsDirty();
control.setValue(newValue, { emitModelToViewChange: false });
});

Plunker Example

另见

关于unit-testing - Angular NgModel双向绑定(bind)单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43183038/

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