2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue.js prototypeに登録したpluginのユニットテストを書く

Last updated at Posted at 2020-05-23

Vue.js で plugin のテストを書いた時のメモ。prototype に登録したプラグインって、どうやって Jest から呼べばいいんだろうってちょっと悩んだ。最終的に localVue.use() してからlocalVue.prototype.$hoge() って実行すればちゃんと Jest からでも実行できた。

テスト対象コード

例えば、HTTP ステータスコードによって処理を行う処理があったとする。本来であればテストしやすいように install とは別ファイルでロジックを管理するべきなんだろうけど。元がこうなっていたので、このコードを保ったままユニットテストを書く。

export const MyPlugin = {
  install(Vue) {
    Vue.prototype.$myPlugin = (statusCode: number) => {
      switch (statusCode) {
        case 401:
          /* 処理省略 */
          break;
        case 500:
          /* 処理省略 */
          break;
        default:
          /* 処理省略 */
          break;
      }
    };
  }
};

テストコード

テストコードはこんな感じ。vue-test-utils の createLocalVue でインスタンスを作成して、 use() でプラグインを適用。その後 prototype から $myPlugin を直接呼べば良い。

import { createLocalVue } from "@vue/test-utils";
import { MyPlugin } from "my-plugin.ts";

const localVue = createLocalVue();
localVue.use(MyPlugin);

describe("MyPlugin", () => {
  it("引数が401の場合", () => {
    localVue.prototype.$myPlugin(401);
  });

  it("引数が500の場合", () => {
    localVue.prototype.$myPlugin(500);
  });
});

Vue のテストコードといえば shallowMount を使ってコンポーネントのユニットテストをよく書いていたけど、いざプラグインのテストを書こうと思ったら、なかなか思い付かず。vue-test-utils は便利。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?