2011-07-22 46 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」類聲明的代碼文件。您還需要關閉腳本標記引用,而不僅僅是。我在自己面前犯了這個錯誤。