1

我正在尝试学习如何使用 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();
  });

});
4

1 回答 1

0

Are these in 2 separate files? I know it sounds like a dumb question but it was a mistake I made when I started with Jasmine. You need to separate your "source" and "spec" files.

Remember to reference your Code file with the "Butthead" class declaration first on your spec runner page. You also need to close your script tag reference with and not just a . I have made this mistake before myself.

于 2011-11-30T07:47:44.620 回答