【问题标题】:How to stub angular-translate promise and verify actions in 'then'如何存根角度翻译承诺并验证“then”中的操作
【发布时间】:2015-01-19 14:27:07
【问题描述】:

我正在使用 angular-translate 翻译一个应用程序,但无法修复我的测试套件。

之前 - 控制器看起来像:

$scope.$on 'new-fetch-controller:step-2', ->
  if EmailUtils.validate(self.contributorEmail)
    ToastService.show "Did you forget to add #{self.contributorEmail}?", 3
    self.addEmail(self.contributorEmail

之前 - 测试看起来像:

    beforeEach inject ($injector) ->
      mockService = $injector.get 'ToastService'

    it 'calls toast service on adding email', ->
      showSpy = @sinon.spy(mockService, 'show')        

      basics.contributorEmail = "test@test.com"
      newFetchScope.nextStep()

      expect(showSpy).to.have.been.calledWith("Did you forget to add test@test.com?", 3)

之后,控制器看起来像(注意对 ToastService 的调用现在是在 promise 的 then 中):

 $scope.$on 'new-fetch-controller:step-2', =>
  if EmailUtils.validate(@contributorEmail)
    $translate('fetches.new.contributors.auto_added', {email: @contributorEmail}).then (translation) ->
      ToastService.show translation, 3

    @addEmail(@contributorEmail)

现在测试失败了:

Failure/Error: expected show to have been called at least once, but it was never called

如何修正我的测试?

【问题讨论】:

    标签: angularjs promise sinon angular-translate


    【解决方案1】:

    我设法解决了这样的测试:

    1. 我将 $translate 服务分配给控制器中的一个变量,因此我可以稍后将其替换为假服务:

      @translate = $翻译

    2. 然后我用一个假翻译服务替换它,该服务返回一个已解决的承诺并调用 scope.$apply() 在期待任何结果之前(注意:'basics' 是我的控制器 - 作为范围别名):

      it 'calls toast service on adding email', ->
        basics.translate = (key) ->
          deferred = $q.defer()
          deferred.resolve('some translation')
      
        deferred.promise
      
        showSpy = @sinon.spy(mockService, 'show')
      
        basics.contributorEmail = "test@test.com"
        newFetchScope.nextStep()
        newFetchScope.$apply()
      
        expect(showSpy).to.have.been.calledWith('some translation', 3)
      

    如果有人有替代解决方案或一般建议 - 请发表您的想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-20
      • 2018-08-25
      • 2016-03-15
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多