Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing components with "Method Style Access" #628

Open
Nemhis opened this issue Jul 25, 2022 · 0 comments
Open

Testing components with "Method Style Access" #628

Nemhis opened this issue Jul 25, 2022 · 0 comments

Comments

@Nemhis
Copy link

Nemhis commented Jul 25, 2022

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:

  • vue 3 (class component)
  • vuex 4
  • typescript
  • jest

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();
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant