Vue Snapshot testing with RouterLinkStub does not render anchor as expected

Viewed 559

I'm trying to run jest-snapshot tests in a Vue application which has a Component with router-link element.
I'm using RouterLinkStub as recommended in Snapshot Testing with Vue-Router

My component template is something like

<template>
  <section class="content">
    <div>
      <router-link to="/" v-slot="{ href, route, navigate }">
        <a :href="href" @click="navigate">
          Homepage
        </a>
      </router-link>
    </div>
  </section>
</template>

The problem is that in snapshot, the router-link renders as empty anchor element (<a />), so if I change the link text the snapshot test stills pass.

This is my snapshot test:

import { RouterLinkStub, shallowMount } from '@vue/test-utils'

import PageNotFound from 'views/PageNotFound.vue'

describe('PageNotFound.vue', () => {
  it('renders as expected', () => {
    const wrapper = shallowMount(PageNotFound, {
      stubs: {
        RouterLink: RouterLinkStub
      }
    })

    expect(wrapper.element).toMatchSnapshot()
  })
})

Can you help me please? Thanks

1 Answers

With Vue 3

 import { shallowMount, RouterLinkStub } from '@vue/test-utils'
 import router from '../../router'

 const findComponentRouterLink = () => 
   wrapper.findComponent(RouterLinkStub)

 const wrapper = shallowMount(Component, {
   global: {
        plugins: [router],
        stubs: {
          RouterLink: RouterLinkStub,
        },
      },
    })

 findComponentRouterLink().text()).toBe('Link text')
Related