【问题标题】:How to mock jQuery with Jasmine如何用 Jasmine 模拟 jQuery
【发布时间】:2015-06-21 11:28:39
【问题描述】:

我想做的事: 我们正在为大量使用 jQuery 的现有 Javascript 代码库编写一些测试。对于测试,我们不希望有实际的 HTML 元素(HTML 固定装置)。如果我们有一个不做任何与 HTML 相关的事情的 jQuery 模拟对象,我们会更喜欢它。

我的出发点:我在这里找到的最有前途的方法:

http://eclipsesource.com/blogs/2014/03/27/mocks-in-jasmine-tests/

这将创建一个辅助方法,该方法通过遍历对象的函数并为每个函数创建一个间谍来创建模拟:

window.mock = function (constr, name) {
  var keys = [];
  for (var key in constr.prototype)
    keys.push( key );
  return keys.length > 0 ? jasmine.createSpyObj( name || "mock", keys ) : {};
};

然后,如果我理解正确,他会这样使用(改编自他的博客文章的示例):

var el = mock($);
el('.some-not-existing-class').css('background', 'red');
expect(el.css).toHaveBeenCalledWith('background', 'red');

但是,这不起作用,因为 elobject 而不是 function

我解决此问题的方法:我重构了他的mock 函数以说明constrfunction 的情况:

mock (constr, name) {
  var keys = [];
  for (var key in constr.prototype)
    keys.push(key);
  var result = keys.length > 0 ? jasmine.createSpyObj(name || "mock", keys) : {};

  // make sure that if constr is a function (like in the case of jQuery), the mock is too
  if (typeof constr === 'function') {
    var result2 = result;
    result = jasmine.createSpy(name || 'mock-fn');
    for (var key in result2)
      result[key] = result2[key];
  }
  return result;
}

但是,测试中的第二行抛出了Cannot read property css of undefined 错误:

var el = mock($);
el('.some-not-existing-class').css('background', 'red');
expect(el.css).toHaveBeenCalledWith('background', 'red');

其他想法:我也尝试将 spy 对象合并到 jQuery 中,但这也无济于事。

有什么想法吗?我希望我们不是唯一没有 HTML 固定装置的人。

【问题讨论】:

    标签: jquery jasmine jasmine-jquery


    【解决方案1】:

    找到了。当我的 mock 函数版本设置为在调用 jQuery 函数时返回 jQuery 对象时,测试有效:

    mock (constr, name) {
      var keys = [];
      for (var key in constr.prototype)
        keys.push(key);
      var result = keys.length > 0 ? jasmine.createSpyObj(name || "mock", keys) : {};
    
      // make sure that if constr is a function (like in the case of jQuery), the mock is too
      if (typeof constr === 'function') {
        var result2 = result;
        result = jasmine.createSpy(name || 'mock-fn');
        result.and.returnValue(result);
        for (var key in result2)
          result[key] = result2[key];
      }
      return result;
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用sinon.js stubs,而不是滚动您自己的辅助方法。

      stub = sinon.stub(jQuery.fn, 'css');
      
      // invoke code which calls the stubbed function
      
      expect(stub.calledWith({ 'background': 'red' })).toBe(true);
      stub.restore();
      

      【讨论】:

      • $('abc').css('background', 'red'); 行作为测试代码进行了尝试。但是,断言失败,sub.calledWith 返回 false。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      • 2021-07-15
      • 2013-08-11
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      相关资源
      最近更新 更多