~/util/axios.js
import axios from 'axios';
const headers = {
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
};
/**
* Next we will register the CSRF Token as a common header with Axios so that
* all outgoing HTTP requests automatically have it attached. This is just
* a simple convenience so we don't have to attach every token manually.
*/
const token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
headers['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
export default axios.create({
headers
});
テストコード
// モックデータ
const responsePayload = {
user: {
id: 1,
email: "syaro-kirima@gochiusa.co.jp",
},
profile: {
id: 1,
userId: 1,
firstName: "シャロ",
lastName: "桐間",
username: "caffeine fighter",
gender: "1",
birthDay: "2000-07-15",
},
};
// axiosをモックする
import axiosMockAdapter from 'axios-mock-adapter';
import axiosClient from '~/util/axios.js';
const axiosMock = new axiosMockAdapter(axiosClient);
axiosMock.onGet('/api/user').reply(200, responsePayload);
- axiosのインスタンスをaxios-mock-adapterに渡してモックオブジェクトを作る
- モックオブジェクトに「こういうときは」「これを返す」という感じに設定していく