Skip to content

Commit

Permalink
tests: demo mocking router
Browse files Browse the repository at this point in the history
  • Loading branch information
lmiller1990 committed Apr 8, 2020
1 parent 653285e commit a2dd554
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 3 deletions.
17 changes: 17 additions & 0 deletions src/components/RouterLinkStub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { defineComponent, h } from 'vue'

// TODO: Borrow typings from vue-router-next
export const RouterLinkStub = defineComponent({
name: 'RouterLinkStub',

props: {
to: {
type: [String, Object],
required: true
}
},

render() {
return h('a', undefined, this.$slots.default())
}
})
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { mount } from './mount'
import { RouterLinkStub } from './components/RouterLinkStub'

export { mount }
export { mount, RouterLinkStub }
3 changes: 2 additions & 1 deletion src/mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ interface MountingOptions<Props> {
mixins?: ComponentOptions[]
mocks?: Record<string, any>
provide?: Record<any, any>
components?: Record<string, Component>
// TODO how to type `defineComponent`? Using `any` for now.
components?: Record<string, Component | object>
directives?: Record<string, Directive>
}
stubs?: Record<string, any>
Expand Down
48 changes: 47 additions & 1 deletion tests/mountingOptions/mocks.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mount } from '../../src'
import { mount, RouterLinkStub } from '../../src'

describe('mocks', () => {
it('mocks a vuex store', async () => {
Expand Down Expand Up @@ -27,4 +27,50 @@ describe('mocks', () => {
await wrapper.find('button').trigger('click')
expect($store.dispatch).toHaveBeenCalledWith('inc')
})

it('mocks vue-router', async () => {
const Foo = {
template: `
<div>
<RouterLink :to="url">Go to post: {{ id }}</RouterLink>
<button @click="submit">Go</button>
</div>
`,
computed: {
url() {
return `/posts/${this.$route.params.id}`
},
id() {
return this.$route.params.id
}
},
methods: {
submit() {
this.$router.push(`/posts/${this.id}`)
}
}
}

const $router = {
push: jest.fn()
}
const $route = {
params: {
id: 1
}
}

const wrapper = mount(Foo, {
global: {
components: {
RouterLink: RouterLinkStub
},
mocks: { $route, $router }
}
})

expect(wrapper.html()).toContain('Go to post: 1')
await wrapper.find('button').trigger('click')
expect($router.push).toHaveBeenCalledWith('/posts/1')
})
})

0 comments on commit a2dd554

Please sign in to comment.