【问题标题】:Jasmine unit test not working with simple jquery click茉莉花单元测试不适用于简单的 jquery click
【发布时间】:2011-07-22 18:41:28
【问题描述】:

我正在尝试学习如何使用 Jasmine 进行单元测试。我设计了一个非常简单的示例,在该示例中,我尝试测试触发 jquery click 事件时是否调用了方法。我似乎无法让它工作。有人可以帮忙吗?非常感谢!!

我收到以下错误:

ReferenceError: Butthead is not defined in http://localhost:4243/spec/buttheadSpec.js (line 11)

spyOn could not find an object to spy upon for responseAlert()

这是代码

function Butthead(){
}

Butthead.prototype.responseAlert = function(){
   alert('You are a butthead');
}

$(document).ready(function(){

  var butthead = new Butthead();

  $('#myButton').click(function(){

      butthead.responseAlert();
  });
} 

这是我的单元测试

// Test Fixture
describe('When clicking myButton', function(){
  var butthead;

  // Set up
  beforeEach(function(){
     butthead = new Butthead(); 
  });


  // Test
  it('should say Hello', function(){

    spyOn(butthead, 'responseAlert');

    $('#myButton').click();

    expect(butthead.responseAlert).toHaveBeenCalled();
  });

});

【问题讨论】:

    标签: jquery unit-testing testing jasmine


    【解决方案1】:

    这些是在 2 个单独的文件中吗?我知道这听起来像是一个愚蠢的问题,但这是我开始使用 Jasmine 时犯的一个错误。您需要将“源”文件和“规范”文件分开。

    请记住首先在规范运行器页面上使用“Butthead”类声明引用您的代码文件。您还需要关闭您的脚本标签引用,而不仅仅是 .我自己也犯过这个错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 2022-01-23
      • 2020-11-25
      • 2015-10-01
      • 2020-08-19
      • 2016-06-14
      相关资源
      最近更新 更多