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.

toHaveBeenCalledWithを使った ...mapActions()の引数付きテスト

Last updated at Posted at 2020-03-14

コンポーネントでのVuexのテスト

Vuexを使用した際に、Vueコンポーネント上でVuexのactionなどが正常に呼び出されたかどうかテストしたい場合があります。

methods: {
  setInitialYear() {
    //setYearが正常に呼び出されているかテストしたい
    this.setYear(initialYear);
  },
  ...mapActions("events", ["setYear"])
}

呼び出されたかどうかだけを調べる場合は、テスト上でコンポーネントを作成する時に、モックしたストアをlocalVueに渡すことで検証が可能です。

参考: Vuex と一緒に使用する

import { mount, createLocalVue } from "@vue/test-utils";
import Vuex from "vuex";
import Id from "@/pages/_id.vue";

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

let store;
let events;

const idFactory = () => {
  events = {
    namespaced: true,
    actions: {
      setYear: jest.fn()
    },
  };
  store = new Vuex.Store({
    modules: {
      events
    }
  });

  return mount(Id, {
    store,
    localVue
  });
};

describe("_id.vue", () => {
  it("setInitialYearを呼んだ際にsetYearが呼ばれる", () => {
    const wrapper = idFactory();
    wrapper.vm.setInitialYear();
    //名前空間.actions.メソッド名で、storeのモックを呼び出せる
    expect(events.actions.setYear).toHaveBeenCalled();
  });
});

しかし、ここはsetYear()が呼び出されているかどうかだけでなく、正しい引数が渡されているかどうかも確認したいところです。

モックしたsetYearが正しい引数を与えられて呼び出されたかどうかを確認するにはtoHaveBeenCalledWith()を使用します。


describe("_id.vue", () => {
  it("setInitialYearを呼んだ際にsetYearが呼ばれる", () => {
    const wrapper = idFactory();
    wrapper.vm.setInitialYear();
    //toHaveBeenCalledWithに変更
    expect(events.actions.setYear).toHaveBeenCalledWith(
      expect.any(Object),
      "2019",
      undefined
    );
  });
});

toHaveBeenCalledWith()の第一引数にはexpect.any(Object)、第二引数にsetYear()に渡している引数、第三引数にはundefinedを設定します。

第一引数のexpect.any()は、引数内で指定したコンストラクタで生成されたものすべてに一致します。つまり、Objectクラスのオブジェクトならマッチします。

わざとテストを失敗させると、第一引数にはcontextオブジェクトが入っていることがわかりました。

 {"commit": [Function anonymous], "dispatch": [Function anonymous], "getters": {}, "rootGetters": {}, "rootState": {"instructions": {}, "users": {}}, "state": {}}

ただ、ここでどうして第一引数にcontextオブジェクトが入り、第三引数にundefinedが入るのか分かりませんでした。どなたかアドバイスをいただけると嬉しいです。

参考: Update examples with module namespace and add unit tests

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?