Bruno Quaresma
Bruno Quaresma

Reputation: 10717

Javascript Test - Verify if Authorization header is correct using axios

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

Upvotes: 3

Views: 4184

Answers (2)

JPRLCol
JPRLCol

Reputation: 200

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

Upvotes: -2

frevib
frevib

Reputation: 453

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.com').reply((config) => {
    return [200, { requestHeaders: config.headers }]
});

const response = await axiosWrapper.get('https://api.com')
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.

Upvotes: 7

Related Questions