2015-10-20 18 views
0

我想學習與茉莉花框架的分機JS和單元測試。我寫了這個方法,我想測試是否用某個值調用decode方法,但是我一直收到標題中提到的錯誤。我在這裏做錯了什麼?茉莉花錯誤:預期的間諜解碼被調用[[]],但實際調用[未定義]

的方法:

onSuccess: function (response) { 
    var text = Ext.decode(response.responseText); 
    this.someGrid.store.loadRawData(text); 
} 

茉莉規格:

it('Function will call decode method', function() { 
    var response = {}; 
    spyOn(Ext, 'decode').and.returnValue([]); 
    me.testObj.onSuccess(response); 
    expect(Ext.decode).toHaveBeenCalledWith([]); 
}) 
+0

我不認爲這個測試是非常有用的。這更多地測試了框架的內部。您最好測試一下商店中的數據是否與您認爲的一致。 –

回答

2

您正在傳遞一個空對象的功能Ext.decode(),因此當函數嘗試訪問responseText它收到未定義的屬性。

// var response = {}; - empty object created in your test 
Ext.decode(response.responseText); 

在你的onSuccess函數調用的returnValue()將返回空數組 - 在你的間諜成立。這個空的數組將被存儲在文本變量中。然後它將被傳遞給loadRawData()函數,而不是decode(),正如您的間諜當前所期待的那樣。

var text = Ext.decode(response.responseText); 
this.someGrid.store.loadRawData(text); 

爲了正確測試,你可以嘲笑響應對象在您的測試包含一個responseText的屬性的函數。而且你還可以添加間諜,並期望爲loadRawData()函數語句,像下面這樣:

it('Function will call decode method', function() { 
    // mock response object has responseText propety 
    var response = { responseText: 'mockResponseText' }; 
    spyOn(Ext, 'decode').and.returnValue([]); 
    // spy to LoadRawData added to check return value of decode is passed on correctly 
    spyOn(me.testObj.someGrid.store, 'loadRawData'); 

    me.testObj.onSuccess(response); 

    // Ext.decode should be called with the response text 
    expect(Ext.decode).toHaveBeenCalledWith('mockResponseText'); 
    // loadRawData should be called with return value of decode function 
    expect(me.testObj.someGrid.store.loadRawData).toHaveBeenCalledWith([]); 
})