最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

testing - Javascript Test - Verify if Authorization header is correct using axios - Stack Overflow

programmeradmin2浏览0评论

I'm using an axios interceptor to set the Authorization token in requests headers.

axios.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer ' + Auth.getToken()
  return config
})

How can i test if my requests are sent with correct token in header?

Ps.: I'm using Mocha + Chai

I'm using an axios interceptor to set the Authorization token in requests headers.

axios.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer ' + Auth.getToken()
  return config
})

How can i test if my requests are sent with correct token in header?

Ps.: I'm using Mocha + Chai

Share Improve this question asked Sep 8, 2016 at 19:52 Bruno QuaresmaBruno Quaresma 10.8k7 gold badges38 silver badges51 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Use axios-mock-adapter to mock Axios, and get the request information from the config object in:

.reply((config) => {})

Example:

import MockAdapter from 'axios-mock-adapter'

const axiosMock = new MockAdapter(axios)

axiosMock.onGet('https://api.').reply((config) => {
    return [200, { requestHeaders: config.headers }]
});

const response = await axiosWrapper.get('https://api.')
expect(response.data.requestHeaders['Authorization'] === 'AUTH_TOKEN')

To test if the correct token is in the header, an integration test would be more approriate. When the correct token is in the header, the API response should be different than when an incorrect token is sent with the request to the API.

If would like to test your headers in the response you could do something like this:

    const mock = new MockAdapter(axios);
    mock.onGet('/anon/getUser').reply(200, {/*response.data*/}, {'my-header-key': 'my-value' });
发布评论

评论列表(0)

  1. 暂无评论