我宣布了一个像这样的组件
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'
};
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');
});
但它为我提供了'fieldLabel'未定义的错误。
如何通过单元测试将数据传递给组件中的@input?
答案 0 :(得分:0)
// 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: [
DND_PROVIDERS ]
})
错误发生在ComponentFixtureAutoDetect中。因为它被称为提供者,所以当数据通过实例传递时它不会检测到更改。所以我们必须使用DetectChanges()函数手动检测更改