Skip to content

Commit

Permalink
feat: allow awaiting setParams
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Jan 11, 2021
1 parent c8b87f0 commit 6d2829d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
26 changes: 21 additions & 5 deletions __tests__/params.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
import { mount } from '@vue/test-utils'
import { watch } from 'vue'
import { getRouter } from '../src'
import Test from './fixtures/Test'

describe('setParams', () => {
it('sets current route params', () => {
getRouter().setParams({ userId: 12 })
const wrapper = mount(Test)
it('sets current route params', async () => {
const router = getRouter()
router.setParams({ userId: 12 })
const wrapper = mount({
template: `<p>{{ $route.params.userId }}</p>`,
})
const spy = jest.fn()

expect(wrapper.vm.$route.params.userId).toBe('12')
watch(wrapper.vm.$route, spy)

expect(wrapper.vm.$route.params).toEqual({ userId: '12' })
expect(wrapper.text()).toBe('12')
expect(spy).toHaveBeenCalledTimes(0)

await router.setParams({ userId: 12 })
expect(spy).toHaveBeenCalledTimes(1)
expect(wrapper.text()).toBe('12')

await router.setParams({ userId: 2 })
expect(spy).toHaveBeenCalledTimes(2)
expect(wrapper.text()).toBe('2')
})
})
6 changes: 4 additions & 2 deletions src/router.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, Ref, ref } from 'vue'
import { Component, nextTick, Ref, ref } from 'vue'
import {
createMemoryHistory,
createRouter,
Expand Down Expand Up @@ -43,7 +43,8 @@ export interface RouterMock extends Router {
getPendingNavigation(): ReturnType<Router['push']>

/**
* Sets the params of the current route without triggering a navigation.
* Sets the params of the current route without triggering a navigation. Can
* be awaited to wait for Vue to render again.
*
* @param params - params to set in the current route
*/
Expand Down Expand Up @@ -184,6 +185,7 @@ export function createRouterMock(options: RouterMockOptions = {}): RouterMock {

function setParams(params: RouteParamsRaw) {
router.currentRoute.value = router.resolve({ params })
return nextTick()
}

const depth = ref(0)
Expand Down

0 comments on commit 6d2829d

Please sign in to comment.