在App.run中使用$ httpBackend捕获$ http

时间:2013-06-23 11:31:48

标签: testing angularjs

我有一个模块App,用于检查用户是否已登录。

App.run ['$rootScope', 'UserService', ($rootScope, UserService) ->
  UserService.current_user()
]

UserService.current_user()会触发$http请求。

那么如何编写$ httpBackend来模拟请求呢?我尝试了一些方法:

describe 'App', ->
  $httpBackend = null

  beforeEach(module('App')) # one
  beforeEach inject ($injector) -> # two
    $httpBackend = $injector.get('$httpBackend')
    $httpBackend
      .when('GET', '/api/1/users/current_user')
      .respond(403, {"error":"not signin"})


  it "should get current_user request", () ->
    $httpBackend.expectGET('/api/1/users/current_user').respond(403, {'error': 'not signin'})

这将显示错误:

Error: Unexpected request: GET /api/1/users/current_user No more request expected

如果我更改# one# two的顺序。它会显示错误

Error: Injector already created, can not register a module!

这让我陷入沮丧。我需要一些帮助。

1 个答案:

答案 0 :(得分:0)

我使用了它:

describe 'App', ->
  beforeEach angular.mock.module('App')

  it "should get current_user request", inject ($httpBackend) ->
    $httpBackend.expectGET('/api/1/users/current_user').respond(403, {'error': 'not signin'})
    $httpBackend.flush()

如果您将后端期望放在每个之前,它也会起作用:

describe 'App', ->
  beforeEach angular.mock.module('App')
  beforeEach inject ($httpBackend) ->
    $httpBackend.expectGET('/api/1/users/current_user').respond(403, {'error': 'not signin'})
    $httpBackend.flush()

  it 'should test someting else', ->

在此Plunker中查看此操作。