【Rails,Vue.js】JestでCSRFトークンを設定したaxiosを含むコンポーネントをテストするとき

事象

JestでCSRFトークンを設定したaxiosインスタンスを含むコンポーネントをマウントする際にTypeError: Cannot read property 'getAttribute' of nullになる

$ npm test
 ● Test suite failed to run

    TypeError: Cannot read property 'getAttribute' of null

       6 |         common: {
       7 |             'X-Requested-With': 'XMLHttpRequest',
    >  8 |             'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
         |                             ^
       9 |         }
      10 |     },
      11 | })

原因

マウントしたコンポーネントCSRFトークンが設定されているmetaタグが含まれていないため

Jestでマウントしたコンポーネントの中身をみると

wrapper = shallowMount(Message)
console.log(wrapper.html())
<div class="container">
    <div class="msg standard my-3"><span>メッセージ</span></div>
</div>

shallowMountしたコンポートにはmetaタグが含まれていない。
そのため、axiosが取得しようとしているmetaタグがないため、エラーになる。

対応

rails-ujsが発行したトークンを設定する

今回の原因がmetaタグからCSRFトークンを設定しているため、metaタグではなくCSRFトークンを発行してくれるモジュールであるrails-ujsを使う。

手順

インストール

npm install @rails/ujs

axiosインスタンスを生成しているファイルを編集する

import axios from 'axios'
import { csrfToken } from '@rails/ujs'; //追加

const http = axios.create({
    headers: {
        common: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': csrfToken() //追加
        }
    },
})


export default http

参考