如何在 Angular 2 中为单元测试创​​建新事件?

Nir*_*jan 3 typescript karma-jasmine angular angular-test

嗨,我正在为我的 angular 代码编写单元测试用例。我正在尝试更新 gridview 中的文本框。下面是我的 gridview 代码。

<input *ngIf="editing[rowIndex + '-scopevalue']" class="inline-editor" autofocus (blur)="updateValue($event, 'scopevalue', value, rowIndex)" type="text" [value]="value" />
Run Code Online (Sandbox Code Playgroud)

下面的函数执行更新。

 updateValue(event, cell, cellValue, rowIndex) {
        this.editing[rowIndex + '-' + cell] = false;
        this.rows[rowIndex][cell] = event.target.value;
        this.rowsCache[rowIndex][cell] = event.target.value;
        this.scopeEdit = this.rows[rowIndex];
        this.updateScope();
    }
Run Code Online (Sandbox Code Playgroud)

在单元测试用例下面,我正在编写检查上面的代码。

 it('update scope name value', () => {
        var row = component.rows[0];
        let cell = 'scopevalue';
        let cellValue = row.scopevalue;
        let rowIndex = 0;
        component.updateValue('/bmw', cell, cellValue, rowIndex);
    });
Run Code Online (Sandbox Code Playgroud)

在上面的方法中,第一个参数应该是事件。有人可以帮助我如何创建活动吗?任何帮助,将不胜感激。谢谢

Adr*_*IER 7

您可以创建一个硬编码值event.target.value并在您的updateValue函数中验证是否rowsCache[rowIndex][cell]具有该值。

你可以用一个简单的对象模拟一个事件,如下所示:

const event = { target: { value: 42 }};
component.updateValue(event, cell, cellValue, rowIndex);
Run Code Online (Sandbox Code Playgroud)

  • 注意:如果您将参数输入为事件对象,则这将不起作用。如果您想使用该类型,则缺少多个属性。 (7认同)

Sum*_* NL 5

如果您的方法的参数被键入为 Event 对象:

const mockEvent: Event = <Event><any>{
  target: {
      value: 42      
  }
};
component.updateValue(mockEvent, cell, cellValue, rowIndex);
Run Code Online (Sandbox Code Playgroud)