服务中then()的角度单元测试

时间:2015-05-16 15:10:31

标签: angularjs unit-testing

我的服务如下:

'use strict'

angular.module('mymodule')
  .factory('myservice', ['$http', ($http) ->
    return {
      get: ->
        return $http.get('/abc/details')
          .then (response) ->
            return response.data
    }
  ])

我的单元测试如下:

describe 'Testing myservice', ->

  _myservice_ = null
  httpBackend = null

  beforeEach module 'mymodule'

  beforeEach inject (myservice, $httpBackend) ->
    _myservice_ = myservice
    httpBackend = $httpBackend


  describe 'When get()', ->
    it "GET request is sent to /abc/details", ->
      httpBackend.whenGET("/abc/details").respond
        data:
          name: 'company name',
          addressee: 'Mary Jane'

      returnedPromise =_myservice_.get()

      result = returnedPromise.then (response) ->
        result = response.data

      httpBackend.flush()
      expect(result).toEqual({name: 'company name', addressee: 'Mary Jane'})

在我的服务中,实际上正在then()处理响应(即仅返回response.data)。我的问题是,我如何(单位)测试myservice.get()是否会返回response.data而不是response

1 个答案:

答案 0 :(得分:1)

由于您的服务不会返回HTTP响应的承诺,而是承诺数据,因此测试应该是

returnedPromise.then (data) ->
     result = data

httpBackend.flush()

expect(result).toEqual({name: 'company name', addressee: 'Mary Jane'})

我还假设真正的REST服务实际上并不返回包含单个数据字段的对象。所以模拟应该看起来像

httpBackend.whenGET("/abc/details").respond
    {
       name: 'company name',
       addressee: 'Mary Jane'
    }

(对不起,如果它是无效的coffeescript。我使用JavaScript)。