[Vuejs]-Axios mock can't handle default headers when using jest

3👍

Here is how you do it for anyone with the same problem. Npm install axios-mock-adapter and then use the following code but change it for your needs.

import actions from "../../src/store/actions";
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
describe('login action', () => {
    it("let the user login and access login success mutator", async() => {


        let mockAdapter = new MockAdapter(axios);

        mockAdapter.onPost('https://hotel-dev.devtropolis.co.uk/api/apilogin').reply(200, {
              token: 'test token',
              user: {username: 'test', password: 'test'}
          });


        const commit = jest.fn()
        const username = 'test'
        const password = 'test'

        await actions.login({commit}, {username, password})

    expect(axios.defaults.headers.common.Authorization).toBe('Bearer test token')

    expect(commit).toHaveBeenCalledWith(
      "LOGIN_SUCCESS",'test token', {username, password})
    })

})

Leave a comment