2011-07-22 50 views
1

我在学习如何用Jasmine进行单元测试。我创建了一个非常简单的示例,我尝试测试在触发jQuery点击事件时调用方法。我似乎无法得到这个工作。有人可以帮忙吗?非常感谢!!茉莉花单元测试不能用简单的jquery点击

我收到以下错误:

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

}); 

回答

0

这些是在2个单独的文件?我知道这听起来像一个愚蠢的问题,但这是我开始茉莉花时犯的一个错误。你需要分离你的“源”和“规格”文件。

请记住在您的spec runner页面上首先引用带有“Butthead”类声明的代码文件。您还需要关闭脚本标记引用,而不仅仅是。我在自己面前犯了这个错误。