【问题标题】:jasmine unit test for javascript CustomEventjavascript CustomEvent 的茉莉花单元测试
【发布时间】:2015-10-01 04:02:24
【问题描述】:

如何测试 jasmine 中是否调度了 CustomEvent?当我尝试运行以下代码时,出现错误:“ReferenceError:找不到变量:CustomEvent”。

function testCustomEvent() {
  window.dispatchEvent(new CustomEvent('myCustomEvent', {
    detail: 'foo'
  }));
}

describe('testCustomEvent', function() {
  it('dispatches myCustomEvent', function() {
    var eventSpy = jasmine.createSpy();
    window.addEventListener('myCustomEvent', eventSpy);

    testCustomEvent();

    expect(eventSpy).toHaveBeenCalledWith('foo');
  });
});

【问题讨论】:

    标签: javascript unit-testing jasmine


    【解决方案1】:

    没有达到预期,因为 eventSpy 是用 { detail: 'foo'} 调用的

    此外,传递的参数是一个新的事件对象,其中包含发送到事件构造函数的参数值。所以它永远不是同一个对象。如果您使用 Jasmine 2.0,则必须使用 partial matcher 强制执行深度部分相等

    expect(eventSpy).toHaveBeenCalledWith(jasmine.objectContaining({
        detail: 'foo'
      }));
    

    如果您使用的是低于 2.0 的版本,请发送 headache

    【讨论】:

      【解决方案2】:

      我认为您的代码的唯一问题是:

      您正在使用toHaveBeenCalledWith 方法而不是toHaveBeenCalled

      Former 用于检查两件事:

      1. 调用了预期的方法
      2. 使用正确的参数调用预期的方法

      尝试运行您的代码here - Try Jasmine。将toHaveBeenCalledWith 替换为toHaveBeenCalled 后。

      注意,不要将任何参数传递给后者。

      【讨论】:

      • 这似乎在 tryjasmine.com 中成功运行。但是,当我使用 github.com/gruntjs/grunt-contrib-jasmine (v0.9.0) 时,我仍然看到相同的错误 - “ReferenceError: Can't find variable: CustomEvent”。
      猜你喜欢
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 2022-01-23
      • 2020-11-25
      • 2020-08-19
      • 1970-01-01
      • 2016-06-14
      相关资源
      最近更新 更多