LoginSignup
9
6

More than 3 years have passed since last update.

vue/test-utils で overwriting methods via the `methods` property is deprecated の警告を消す

Last updated at Posted at 2020-08-29

表題の通り、@vue/test-utilsDeprecatedを由来とするコンソールエラーを非表示にする方法です。

環境

  • @vue/test-utils v1.0.4
  • Vue.js v2.6.11

事象

テスト実行時に下記のようなコンソールエラーが出ます。

[vue-test-utils]: overwriting methods via the `methods` property is deprecated and will be removed in the next major version. There is no clear migration path for the `methods` property - Vue does not support arbitrarily replacement of methods, nor should VTU. To stub a complex method extract it from the component and test it in isolation. Otherwise, the suggestion is to rethink those tests.

どんなテストコードを書いているかというと、下記のようなコードです。

    const methods = {
      setUpXXXXX: jest.fn(),
    }

    const computed = {
      user () {
        return {}
      },
    }

    const wrapper = shallowMount(Component, {
      localVue,
      vuetify,
      router,
      stubs,
      methods,
      computed,
    })

上記のように、methodscomputedをテストコードから上書きしてモックなどに差し替える方法はVue2.xのテストコードを書く上では便利なのですが、@vue/test-utils v1.0.4時点でDeprecatedとなっております。

これは、Vue3以降でcomposition-apiに対応するため、これからはcomposableとしてこれらの処理は全てまとめて切り出し、単体テストを書く流れになることから、methods/computedをVueインスタンスにinjectするようなテスト手法は終りを迎えるという意味だと思っています(これは仮説)。

とはいえ、特にNuxt.jsのユーザーの場合は2020年9月現在、まだしばらくはVue2のテストコードを書かなければいけないでしょう。というか僕がそうです(nuxt-composition-apiのメジャーバージョンが待ち遠しい)。

対策

対象のテストファイルの冒頭に下記のコードを差し込めば、Deprecatedを由来としたコンソールエラーは消えます。

import { config } from '@vue/test-utils'

config.showDeprecationWarnings = false

よく見たら公式リポジトリにも書いてました。
https://github.com/vuejs/vue-test-utils/blob/869b096253e1af0b6121bd4529fa1adc47fda934/docs/api/config.md

こちらのソースを見ると、warnDeprecatedの動作自体が上記Configをもとにして判断していたので、Falseにすればいいのだとわかりました。
https://github.com/vuejs/vue-test-utils/blob/39be102165f94897786db3b9db51af09ad419187/packages/shared/util.js

まとめ

コンソールエラーを汚されると、肝心のコンポーネント読み込み失敗などのWarningが埋もれてしまうので消しました。showDeprecationWarningsgrepしたら今後Vue3への移行時にも対応できると思うので、一時的な対応ではありますがあとでちゃんと移行することを念頭に置いて実装しましょう。

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6