diff --git a/src/__tests__/useMutations.test.ts b/src/__tests__/useMutations.test.ts new file mode 100644 index 0000000..b2b814a --- /dev/null +++ b/src/__tests__/useMutations.test.ts @@ -0,0 +1,39 @@ +import useMutations from '../useMutations'; +import renderHook from '../util/renderHook'; + +interface InjectMutations { + increment: Function; + decrement: Function; +} + +describe('useMutations', () => { + it('should be defined', () => { + expect(useMutations).toBeDefined(); + }); + + it('should be defined mutations', () => { + const { vm } = renderHook(() => ({ + ...useMutations(['increment']), + ...useMutations('test', ['decrement']), + })); + + expect(vm.increment).toBeDefined(); + expect(vm.decrement).toBeDefined(); + }); + + it('should update count state', () => { + const { vm } = renderHook(() => ({ + ...useMutations(['increment']), + ...useMutations('test', ['decrement']), + })); + + expect(vm.$store.state.count).toBe(0); + expect(vm.$store.state.test.count).toBe(0); + + vm.increment(); + vm.decrement(); + + expect(vm.$store.state.count).toBe(1); + expect(vm.$store.state.test.count).toBe(-1); + }); +}); diff --git a/src/useMutations.ts b/src/useMutations.ts new file mode 100644 index 0000000..7f5abd3 --- /dev/null +++ b/src/useMutations.ts @@ -0,0 +1,17 @@ +import { mapMutations } from 'vuex'; +import { MapperMutations } from './ts'; +import { getRuntimeVM } from './util/runtime'; + +const useMutations: MapperMutations = (...args) => { + // @ts-ignore + const mutations = mapMutations(...args); + const vm = getRuntimeVM(); + const mapper = {}; + Object.keys(mutations).forEach((key) => { + mapper[key] = mutations[key].bind(vm); + }); + + return mapper; +}; + +export default useMutations;