LoginSignup
2

More than 5 years have passed since last update.

AngularJSでInterceptorのHeaderはどのようにテストするか?

Last updated at Posted at 2014-09-14

例えば\$httpのリクエストをインターセプトして、Authorizationヘッダーにトークンを付与するInterceptorを作成したとする。

この場合、このInterceptorのサービスをどのようにテストするのがよいのか?

で、調べたら大変素晴らしい記事があったのでそちらを参考にテストを書いた。

トークンを管理しているサービス、Authorizationヘッダーを付与するInterceptorサービス、モックの\$httpBackend,あとはInterceptorが登録されているはずの \$httpProviderを読み込んでる。

auth_interceptor_spec.coffee
'use strict'

describe 'Service: AuthInterceptor', ->
  $httpProvider = {}
  beforeEach module 'gambaApp', (_$httpProvider_)->
    $httpProvider = _$httpProvider_
    return

  AuthInterceptor = {}
  AuthToken = {}
  $httpBackend = {}
  beforeEach inject (_AuthInterceptor_, _AuthToken_, _$httpBackend_) ->
    $httpBackend = _$httpBackend_
    AuthInterceptor = _AuthInterceptor_
    AuthToken = _AuthToken_

  afterEach inject (_AuthToken_) ->
    _AuthToken_.clear()

  token = 'SecureToken'
  tokenString = "Token token=\"#{token}\""

  it "AuthInterceptorが定義されていること", ->
    expect(AuthInterceptor).toBeDefined()

  it "AuthInterceptorがインターセプターに登録されていること", ->
    expect($httpProvider.interceptors).toContain "AuthInterceptor"

  it 'トークンがセットされていない場合Authorizationがセットされていないこと', ->
    config = AuthInterceptor.request({headers: {}})
    expect(config.headers.Authorization).toBeUndefined()

  it 'トークンが保持されている場合setting後Authorizationにセットされること', ->
    AuthToken.setToken(token)
    config = AuthInterceptor.request({})
    expect(config.headers.Authorization).toBe tokenString

  it 'トークンが保持されて通信されるときはAuthorizationにセットされていること', ->
    AuthToken.setToken(token)
    $httpBackend.whenGET('/api/users', (headers)->
      expect(headers.Authorization).toBe tokenString
    )

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2