【问题标题】:Jasmine - testing promises. How to test function in callback?Jasmine - 测试承诺。如何在回调中测试函数?
【发布时间】:2016-12-18 12:17:30
【问题描述】:

我有(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
      });
    });
  };
}

或咖啡脚本:

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() 调度函数。关于如何去做的任何想法?

【问题讨论】:

  • 在您的测试中,您必须发送 API 请求然后对其进行测试。然后您可以使用toHaveBeenCalledWith() 功能。我建议查看这篇文章:htmlgoodies.com/html5/javascript/…
  • 谷歌茉莉异步测试。有很多东西。请在发布到 Stack Overflow 之前进行研究,如果文档中有您不理解的内容,请将其包含在问题中。

标签: javascript angularjs unit-testing coffeescript jasmine


【解决方案1】:
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()

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 2018-07-27
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 2018-11-15
    • 2015-03-05
    • 1970-01-01
    • 2014-10-31
    相关资源
    最近更新 更多