diff --git a/README.md b/README.md index 45db469..6d7716d 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ export default createComponent({ ## Hooks +- [`useRouter`](./src/useRouter.ts) — A hook for [`vue-router`](https://github.com/vuejs/vue-router). - [`useDate`](./src/useDate.ts) — Using [`dayjs`](https://github.com/iamkun/dayjs) to process date. - [`useWindowSize`](./src/useWindowSize.ts) — Tracks `window` dimensions. diff --git a/src/__tests__/useRouter.test.ts b/src/__tests__/useRouter.test.ts new file mode 100644 index 0000000..635b2cb --- /dev/null +++ b/src/__tests__/useRouter.test.ts @@ -0,0 +1,33 @@ +import VueRouter, { Route } from 'vue-router'; +import useRouter from '../useRouter'; +import renderHook from '../util/renderHook'; + +declare module 'vue/types/vue' { + interface Vue { + route: Route; + router: VueRouter; + } +} + +describe('useRouter', () => { + it('should be defined', () => { + expect(useRouter).toBeDefined(); + }); + + it('shuold have route', () => { + const { vm } = renderHook(useRouter); + expect(vm).toHaveProperty('route'); + expect(vm).toHaveProperty('router'); + }); + + it('should route to be correct', () => { + const { vm } = renderHook(useRouter); + expect(vm.route.name).toBe('index'); + expect(vm.route.meta.title).toBe('Vue Hooks'); + + vm.router.push('/test'); + + expect(vm.route.name).toBe('404'); + expect(vm.route.meta.title).toBe('404 - Not Found'); + }); +}); diff --git a/src/useRouter.ts b/src/useRouter.ts new file mode 100644 index 0000000..fb26ecd --- /dev/null +++ b/src/useRouter.ts @@ -0,0 +1,8 @@ +import { computed } from 'vue-function-api'; +import withContext from './util/withContext'; + +export default withContext(function useRouter(vue) { + const route = computed(() => vue.$route); + const router = computed(() => vue.$router); + return { route, router }; +}); diff --git a/src/util/renderHook.ts b/src/util/renderHook.ts index d78e01f..3f94775 100644 --- a/src/util/renderHook.ts +++ b/src/util/renderHook.ts @@ -1,17 +1,44 @@ /* eslint import/no-extraneous-dependencies: off */ -import Vue from 'vue'; +import { shallowMount, createLocalVue } from '@vue/test-utils'; import { plugin, createComponent } from 'vue-function-api'; -import { mount } from '@vue/test-utils'; +import VueRouter from 'vue-router'; -Vue.use(plugin); +const localVue = createLocalVue(); + +localVue.use(VueRouter); +localVue.use(plugin); + +const router = new VueRouter({ + routes: [ + { + path: '/', + name: 'index', + meta: { title: 'Vue Hooks' }, + }, + { + path: '*', + name: '404', + meta: { title: '404 - Not Found' }, + }, + ], +}); export default function renderHook(hook: Function) { - const vm = createComponent({ - template: `
`, - setup() { - return hook(); + const App = createComponent({ + template: ` +