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

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

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' });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745347176a4623607.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信