茉莉花 - 测试承诺。如何在回调中测试函数?

时间:2016-08-11 16:31:26

标签: javascript angularjs unit-testing coffeescript jasmine

我有(Angular.js 1.5 + ng-redux)代码:

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:

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

我想编写一个测试,以查看是否已使用正确的参数对API发出请求。 我还会检查是否调用.then()调度函数。关于如何去做的任何想法?

1 个答案:

答案 0 :(得分: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()