【问题标题】:Angular 2 testing with ngModel and ngModelChange使用 ngModel 和 ngModelChange 进行 Angular 2 测试
【发布时间】:2016-04-15 11:26:01
【问题描述】:

我正在尝试围绕文本输入测试包装器组件。

我的组件如下所示:

@Component({
selector: 'my-textbox',
inputs: ['inputModel', 'label'],
outputs: ['inputModelChange'],    
template: `  

    <div ngForm class="field">
        <label>{{ label }}</label>            
        <input type="text" ngControl="{{ control }}" #item="ngForm" [ngModel]="inputModel" (ngModelChange)="setTextValue($event)">
    </div>
    `
})

export class IslTextboxComponent {

control;
inputModel: Object;
inputModelChange: EventEmitter<any> = new EventEmitter();
label: string;

constructor() {
    this.control = 'text'+ Math.floor(Math.random()*11);
}

setTextValue(newValue): void {
    this.inputModel = newValue;
    this.inputModelChange.emit(newValue);
}
}

这是我的测试:

describe('My Textbox Component', () => {

it('should show modify input model',
    injectAsync([TestComponentBuilder], (tcb) => {
        return tcb
            .createAsync(MyTextboxComponent)
            .then((fixture) => {

                let nativeElement = fixture.nativeElement;

                fixture.detectChanges();                   

                let input = nativeElement.querySelector('input');

                input.value = 'VALUE_TO_TEST';

                //???
                input.dispatchEvent(new Event('input'));                    

                fixture.detectChanges();                                  

                expect(nativeElement.inputModel).toBe('VALUE_TO_TEST');

            });
    }));

});

我想在文本框中输入文本并让 inputModel 自行更新,但没有触发事件。如何使 ngModelChange 事件触发? inputModel 永远不会更新...

【问题讨论】:

    标签: angular


    【解决方案1】:
    let input = nativeElement.querySelector('input');
    input.value = 'VALUE_TO_TEST';
    let evt = document.createEvent('Event');
    evt.initEvent('input', true, false);
    setTimeout(expect(x).ToBe(z),1000);
    

    你快到了。

    • setTimeout 是关于让 Change-Detection 运行一秒钟。 (以后可以减少)。
    • createEvent 将 EventInterface-Name 作为参数,而 initEvent 正在定义它。 “事件”是最基本的,没有负载。
    • changeDetection 不需要在输入后手动触发,因为您触发了视图上的事件。

    【讨论】:

    • 我已经尝试过你的代码,我正在测试 expect(fixture.componentInstance.inputModel).toBe('VALUE_TO_TEST')expect(nativeElement.inputModel).toBe('VALUE_TO_TEST') 但它们都未定义,我可以检查什么以确保模型已更新?
    猜你喜欢
    • 2017-03-07
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    相关资源
    最近更新 更多