๐ŸŽฏ 5.3 ้žๅŒๆœŸ Vuex action ใฎใƒ†ใ‚นใƒˆๆ›ธใๆ›ใˆ

๏ผˆComposition API + Jest ใซใŠใ‘ใ‚‹ Promise ใ‚’่ฟ”ใ™ action ใฎใƒ†ใ‚นใƒˆ๏ผ‰


โœ… ใ€่ฆ็‚นใ€‘

โ†’ Composition API ใธใฎๆ›ธใๆ›ใˆๅพŒใ‚‚ใ€ๅŸบๆœฌใฎใƒ†ใ‚นใƒˆๆ–น้‡ใฏๅค‰ใ‚ใ‚‰ใชใ„ใŒใ€

โ†’ this.$store.dispatch โ†’ useStore().dispatch ใซใชใ‚‹ใ€‚


๐ŸŸข ใ€้žๅŒๆœŸ action ใฎไพ‹๏ผˆComposition API + Vuex๏ผ‰ใ€‘

// store/counter/actions.ts
export const actions = {
  async incrementAsync({ commit }: any) {
    await new Promise((resolve) => setTimeout(resolve, 500)); // 500ms ๅพ…ใค
    commit('increment');
  },
};


๐ŸŸ  ใ€ใ‚ฏใƒฉใ‚นใ‚ณใƒณใƒใƒผใƒใƒณใƒˆๆ™‚ใฎใƒ†ใ‚นใƒˆ๏ผˆBefore๏ผ‰ใ€‘

it('incrementAsync ใฏ increment ใ‚’ commit ใ™ใ‚‹ (ใ‚ฏใƒฉใ‚น็‰ˆ)', async () => {
  const commit = jest.fn();
  await actions.incrementAsync({ commit });
  expect(commit).toHaveBeenCalledWith('increment');
});


๐ŸŸฃ ใ€Composition API ๆ™‚ใฎใƒ†ใ‚นใƒˆ๏ผˆAfter๏ผ‰ใ€‘

action ใฎๅ˜ไฝ“ใƒ†ใ‚นใƒˆใฏๅŸบๆœฌ็š„ใซๅค‰ใ‚ใ‚‰ใชใ„๐Ÿ‘‡

// tests/counter.actions.spec.ts
import { actions } from '@/store/counter/actions';

describe('counter actions (Composition API)', () => {
  it('incrementAsync ใฏ increment ใ‚’ commit ใ™ใ‚‹', async () => {
    const commit = jest.fn();                      // โ† commit ใ‚’ใƒขใƒƒใ‚ฏ
    await actions.incrementAsync({ commit });      // โ† Promise ใŒ็ต‚ใ‚ใ‚‹ใพใงๅพ…ใค
    expect(commit).toHaveBeenCalledWith('increment');
  });
});