2016-08-11 71 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()