ktsn / vuex-smart-module

Type safe Vuex module with powerful module features
MIT License
381 stars 19 forks source link

Testing components with "Method Style Access" #628

Open Nemhis opened 2 years ago

Nemhis commented 2 years ago

Hi! Could you please give an example of how to test components using "Method Style Access"? I can't figure out how I can do this:(

pre requirements:

A simple example below

store module:

import {
  Actions,
  Context,
  Getters,
  Module,
  Mutations,
} from 'vuex-smart-module';
import api from '@/api';

export class UserState {}
export class UserGetters extends Getters<UserState> {}
export class UserMutations extends Mutations<UserState> {}
export class UserActions extends Actions<
  UserState,
  UserGetters,
  UserMutations,
  UserActions
> {
  logout(): Promise<unknown> {
    return api.logout().then();
  }
}

const module = new Module({
  state: UserState,
  getters: UserGetters,
  mutations: UserMutations,
  actions: UserActions,
});

export type UserModule = Module<
  UserState,
  UserGetters,
  UserMutations,
  UserActions
>;
export type UserStore = Context<UserModule>;

export { module as default };

component:

<template>
  <button @click="logout" type="button">Logout</button>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-property-decorator';
import userModule, { UserStore } from '@/store/user';
import store from '@/store';

@Options({})
export default class LogoutBtn extends Vue {
  userStore: UserStore = userModule.context(store);

  logout(): void {
    this.userStore.actions.logout().then();
  }
}
</script>

Test

import { mount, VueWrapper } from '@vue/test-utils';
import LogoutBtn from './LogoutBtn.vue';
import { Plugin } from 'vue';

describe('LogoutBtn', () => {
  let wrapper: VueWrapper;

  const createComponent = <T>(options: T, store?: Plugin) => {
    wrapper = mount(LogoutBtn, {
      ...options,
      global: {
        plugins: [store],
      },
      shallow: true,
    });
  };

  afterEach(() => {
    wrapper.unmount();
  });

  it('Call logout action on btn click', async () => {
    const logout = jest.fn();
    createComponent({});

   // TODO: how to mock store ? how to check logout call ?
    expect(logout).toHaveBeenCalled();
  });
});