【问题标题】:How to create new event for unit testing in Angular 2?如何在 Angular 2 中为单元测试创​​建新事件?
【发布时间】:2018-10-31 23:13:56
【问题描述】:

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

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

下面的函数执行更新。

 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();
    }

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

 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);
    });

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

【问题讨论】:

  • 我不知道这是否是您想要的,但您可以创建一个硬编码的 event.target.value 值并在您的 updateValue 函数中验证 rowsCache[rowIndex][cell] 是否具有该值。你可以用一个简单的对象来模拟事件,像这样:const event = { target: { value: 42 }}; component.updateValue(event, cell, cellValue, rowIndex);
  • 是的,这就是我想要的。谢谢
  • 不错!我写了解决方案:)

标签: angular typescript karma-jasmine angular-test


【解决方案1】:

您可以将event.target.value 设为硬编码值,并在updateValue 函数中验证rowsCache[rowIndex][cell] 是否具有该值。

你可以用一个简单的对象来模拟一个事件,像这样:

const event = { target: { value: 42 }};
component.updateValue(event, cell, cellValue, rowIndex);

【讨论】:

  • 注意:如果您将参数键入为 Event 对象,这将不起作用。如果您想使用该类型,则缺少几个属性。
  • @TheCodeFox 你知道这个问题的任何解决方案吗?我们不能完全模拟 Event 对象,这是浪费时间,typecast 也不起作用
  • @RaphaëlVO 对我来说这对我有用:stackoverflow.com/a/47713088/3876419,基本上是创建一个对象const mockEvent : Event = &lt;Event&gt;&lt;any&gt;{ //insert your target value here };
  • 如果我没记错的话,这个mock不能直接作为Event使用,需要对它进行typecast以防止编译错误,像这样:mock as unknown as Event
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 2017-04-29
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多