【问题标题】:HowTo properly test Angular's $http success and error promise with sinon.js?如何使用 sinon.js 正确测试 Angular 的 $http 成功和错误承诺?
【发布时间】:2015-05-28 14:28:00
【问题描述】:

如何使用 sinon.js 正确测试 Angular 的 $http successerror 承诺?这是我到目前为止所拥有的(全部在咖啡脚本中):

服务高速公路

drive: (vehicle) ->
  $http.post '/user/signin', vehicle
  .success ((data) ->
    # do stuff
    return data
  ).error
    throw Error (error)

控制器街道

$scope.drive = (vehicle) ->
    $scope.data = Autobahn.drive(vehicle)

单元测试 w。诗乃

it 'should test $http callbacks', ->
  sinon.stub($scope, 'drive').yieldsTo 'success', callBackMockData
  $scope.drive vehicle, (data) ->
    expect($scope.data).to.be(callBackMockData)
    return
  return

结果

TypeError: 'undefined' is not a function (evaluating '(function(data) {
          return data;
        }).error(function(data) {
          throw Error(error);
        })')

也许存根不是正确的方法,因为我想一次性真正测试控制器和服务。我们如何测试 Angular 的 $http 承诺?官方文档使用 httpBackEnd 未能提供有关如何测试 $http 回调链的详细信息。

【问题讨论】:

    标签: angularjs unit-testing sinon


    【解决方案1】:

    不要使用$httpsuccesserror 承诺。 $http 本身就是一个承诺。使用.then()

    见:Undefinied is not a function when using .success on a function that returns a promise

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 2017-05-20
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多