DEV Community

Manish Kumar
Manish Kumar

Posted on

URL-Synchronized Pagination in Vue 3: Typing RoutePagination and Testing External Behavior

In data-heavy dashboards, tables, and issue trackers, pagination should always synchronize with the browser's URL query parameters. Storing the active page number in ?page=X enables users to share direct links, bookmark filtered views, and use browser back/forward buttons seamlessly.

In my recent contribution to GitLab's Contributors Platform (MR !3200), I migrated the shared RoutePagination component and its unit test suite to TypeScript.

Beyond adding type annotations, this migration provided an opportunity to modernize the component's two-way binding using Vue 3.4's defineModel() macro and refactor the test suite from inspecting internal component state to asserting user-facing behavior.


1. Modernizing Two-Way Binding with defineModel<number>()

Previously, RoutePagination.vue relied on runtime prop definitions and untyped model declarations:

<!-- Before (JavaScript) -->
<script setup>
const props = defineProps({
  totalRows: { type: Number, required: true },
  perPage: { type: Number, required: true },
});

const currentPage = defineModel({ required: false, type: Number });
const router = useRouter();
const route = useRoute();

const onPageChange = (newPage) => {
  router.push({ query: { ...route.query, page: newPage } });
};
</script>
Enter fullscreen mode Exit fullscreen mode

The TypeScript Refactoring

In the migrated version, we introduced compile-time type declarations and handled asynchronous router promises cleanly:

<!-- After (TypeScript) -->
<script setup lang="ts">
import { BPagination } from 'bootstrap-vue-next';
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { numberParam } from '~/common/QueryParams';

const props = defineProps<{
  totalRows: number;
  perPage: number;
}>();

// Strongly typed two-way v-model binding
const currentPage = defineModel<number>();

const router = useRouter();
const route = useRoute();

const onPageChange = (newPage: number | string) => {
  const query = route.query;
  // Explicitly void floating navigation promise
  void router.push({ query: { ...query, page: newPage } });
};

onMounted(() => {
  const page = numberParam(route.query.page) || 1;
  currentPage.value = page;
});
</script>
Enter fullscreen mode Exit fullscreen mode

Key Technical Details:

  • defineModel<number>(): Replaces manual modelValue prop and update:modelValue emit declarations with Vue 3.4's type-safe macro.
  • Handling Floating Promises (void router.push): Calling asynchronous routing methods without await can trigger @typescript-eslint/no-floating-promises. Adding void explicitly marks the promise as intentionally unawaited in event callbacks.

2. Refactoring Specs: Testing External Contracts, Not Internal State

In older specs, unit tests frequently inspected component internals using wrapper.vm:

// ❌ Old Anti-Pattern: Checking private component internals
expect(wrapper.vm.currentPage).toBe(2);
Enter fullscreen mode Exit fullscreen mode

While wrapper.vm works in JavaScript, relying on it creates fragile tests that break whenever internal variable names change. It also creates typing friction in TypeScript because wrapper.vm is not strictly typed unless heavily annotated.

The Modernized Spec

In RoutePagination.spec.ts, we refactored assertions to observe what the user and parent components actually observe:

  1. Child Props: Verifying what the underlying <BPagination> component receives.
  2. Emitted Events: Verifying what update:modelValue emits to the parent.
  3. URL State: Verifying what router.currentRoute.value.query reflects.
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils';
import { BPagination } from 'bootstrap-vue-next';
import type { Router } from 'vue-router';
import { createTestRouter } from '~/spec/testHelpers';
import RoutePagination from './RoutePagination.vue';

const defaultProps = { totalRows: 10, perPage: 5 };

let router: Router;
let wrapper: VueWrapper;
const createWrapper = (props = {}) => {
  wrapper = mount(RoutePagination, {
    props: { ...defaultProps, ...props },
    global: { plugins: [router] },
  });
};

const findBPagination = () => wrapper.findComponent(BPagination);
const findPage2Button = () => findBPagination().find('button[aria-posinset="2"]');

beforeEach(async () => {
  router = await createTestRouter('/leaderboard');
});

describe('changing page', () => {
  it('updates route and emits current page', async () => {
    createWrapper();

    await findPage2Button().trigger('click');
    await flushPromises();

    // Asserting actual URL query change
    expect(router.currentRoute.value.query).toStrictEqual({ page: '2' });

    // Asserting child UI received modelValue update
    expect(findBPagination().props('modelValue')).toBe(2);
  });
});
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  1. Use defineModel<T>(): Simplifies component code by replacing separate prop/emit definitions with a single typed reactive reference.
  2. Handle Router Promises: Use void router.push(...) in event handlers where awaiting the navigation is unnecessary.
  3. Test the Black Box: Test emitted events and child component props rather than private wrapper.vm properties. Tests will be sturdier and easier to type.

Check out the merged Merge Request on GitLab:

👉 GitLab Contributors MR !3200


Author: Manish Kumar

GitLab: @manishpatel00

Top comments (0)