我宣布了一个像这样的组件
export class Component {
private selectedFieldType: string;
private enableAddCheck: boolean = false;
@Input('itemX') item;
}
我有一个像这样的两个绑定的HTML
Field : <input [(ngModel)]="item.fieldLabel" type="text" class="input-bars">
所以我创建了像这样的单元测试代码来检查这样的双向绑定
beforeEach(async(() => {
// refine the test module by declaring the test component
TestBed.configureTestingModule({
imports: [ FormsModule ],
declarations: [Component , DND_DIRECTIVES],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
providers: [
{ provide: ComponentFixtureAutoDetect, useValue: true },
DND_PROVIDERS ]
})
// create component and test fixture
fixture = TestBed.createComponent(Component );
// get test component from the fixture
comp = fixture.componentInstance;
}));
it('To check fieldLabel to way binding from inputbox to data', () => {
comp.item = {
fieldLabel: 'text'
};
comp.ngOnInit();
fixture.detectChanges();
let fieldTypeInput: HTMLInputElement;
const input = fixture.debugElement.query(By.css('input'));
fieldTypeInput = input[0].nativeElement;
fieldTypeInput.value = 'field';
fixture.detectChanges();
expect(comp.item.fieldLabel).toBe('field');
});
但是它正在给予&#39; fieldLabel&#39;对我来说是未定义的错误。
如何通过单元测试将数据传递给组件中的@input?
答案 0 :(得分:1)
手动更改后,更改输入值
fieldTypeInput.value = 'field';
您仍然需要调度输入事件。它不会因为您更改值而发生。该事件是Angular侦听的事件,以便获取新值来处理
import {dispatchEvent} from '@angular/platform-browser/testing/browser_util';
fieldTypeInput.value = 'field';
dispatchEvent(fieldTypeInput, 'input');
此外,由于事件处理是异步的,您需要等待它稳定。为此,您可以使用fixture.whenStable
,但之后还需要进行测试async
import { async } from '@angular/core/testing'
it('..', async(() => {
...
fieldTypeInput.value = 'field';
dispatchEvent(fieldTypeInput, 'input');
fixture.whenStable().then(() => {
// do expectations here
})
})