2016-08-11 60 views
1

我已經(Angular.js 1.5 + NG-終極版)代碼:如果請求API已取得茉莉花 - 測試承諾。如何在回調中測試函數?

update: (itemId, value) -> (dispatch, getState) -> 
    params = { 
    id: itemId, 
    action: value 
    } 
resultsAPI.change(params).then(results) -> 
    dispatch({ 
    type: "CHANGE_STATE" 
    itemId: itemId 
    output: results 
    }) 

我想要寫一個測試看:

update: function(itemId, value) { 
    return function(dispatch, getState) { 
    var params; 
    params = { 
     id: itemId, 
     action: value 
    }; 
    resultsAPI.change(params).then(function(results) { 
     dispatch({ 
     type: "CHANGE_STETE", 
     itemId: itemId, 
     output: results 
     }); 
    }); 
    }; 
} 

或CoffeeScript的具有正確的參數。 我還會檢查.then()派遣函數是否被調用後。任何想法如何去做呢?

+0

在您的測試中,您必須發送API請求,然後對其進行測試。然後你可以使用'toHaveBeenCalledWith()'功能。我建議查看本文:http://www.htmlgoodies.com/html5/javascript/spy-on-javascript-methods-using-the-jasmine-testing-framework.html#fbid=ZMd4zHJBGuC –

+0

Google茉莉花異步測試。有很多東西。在發佈到Stack overflow之前,請做研究,如果有某些你不明白的文檔,請在問題中加入。 –

回答

0
it "call dispatch after .then", -> 
    filterId = 1 
    value = "stop" 

    params = 
    id: filterId 
    action: value 

    dispatch = jasmine.createSpy("dispatch") 
    dispatch = => 
     type: "CHANGE_STATE" 
     filterId: 2 

    spyOn(@resultsAPI, "change").and.callFake(-> dispatch()) 
    @ngRedux.dispatch(update()) 
    @InvestigationsResultsAPI.changeState(params) 
    dispatch() 
    expect(dispatch).toHaveBeenCalled()