Giter Club home page Giter Club logo

Comments (5)

johnwebbcole avatar johnwebbcole commented on September 26, 2024 1

Thanks, I was able to get it working. I expanded the router-link-stub above to render the link and the to property. There may be a better way, but this works for me.

import util from 'util';

export const RouterLinkStub = {
  name: 'router-link-stub',
  render(h) {
    return h(
      'router-link',
      {
        attrs: Object.keys(this._props).reduce((attrs, key) => {
          attrs[key] = util.inspect(this._props[key]);
          return attrs;
        }, {})
      },
      this.$slots.default
    );
  },
  props: ['to']
};

And my test becomes:

import { shallow } from 'vue-test-utils';
import { compileToFunctions } from 'vue-template-compiler';
import { createRenderer } from 'vue-server-renderer';
import GoHome from '@/components/GoHome.vue';
import { RouterLinkStub } from '../utils';

describe('GoHome.vue', () => {
  it('renders a router-link with a path', () => {
    const wrapper = shallow(GoHome, {
      stubs: { 'router-link': RouterLinkStub },
      propsData: { path: 'helloworld' },
      slots: { default: compileToFunctions('<div>Hello World</div>') }
    });

    // make sure the `to` attribute exists.
    expect(wrapper.element.getAttribute('to'));

    const renderer = createRenderer();
    renderer.renderToString(wrapper.vm, (err, str) => {
      if (err) throw new Error(err);
      expect(str).toMatchSnapshot();
    });
  });
});

which renders the following snapshot:

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`GoHome.vue reners a router-link with a path 1`] = `
<router-link to="{ name: 'Home', params: { path: 'helloworld' } }">
    <div>Hello World</div>
</router-link>
`;

from vue-test-utils.

eddyerburgh avatar eddyerburgh commented on September 26, 2024 1

We now include a RouterLink component. You can stub RouterLink like this:

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

const wrapper = mount(Component, {
  stubs: {
    RouterLink: RouterLinkStub
  }
})

wrapper.find(RouterLinkStub)

from vue-test-utils.

johnwebbcole avatar johnwebbcole commented on September 26, 2024

I'd love an answer and a good example for doing exactly this. This is the top search result for vue-test-utils router-link, so I'm going to ask here.

I'm trying to test a simple component that has a <router-link> in it, and I'm having troubles getting it to work at all. To test my setup, which is using jest, I copied the List.vue file and test from the jest example. This test runs fine.

My component, GoHome.vue:

<template>
<router-link :to="{name: 'Home', params: { path: this.path }}"><slot></slot></router-link>
</template>
<script>
export default {
  name: 'GoHome',
  props: ['path']
};
</script>

and my test GoHome.spec.js

import { shallow } from 'vue-test-utils';
import { compileToFunctions } from 'vue-template-compiler';
import GoHome from '@/components/GoHome.vue';

describe('GoHome.vue', () => {
  it('displays default message', () => {
    const wrapper = shallow(GoHome, {
      stub: ['router-link'],
      propsData: { to: 'helloworld' },
      slots: { default: compileToFunctions('<div>Hello World</div>') }
    });
    var bar = wrapper.find('router-link').hasProp('to', 'helloworld');
    var foo = wrapper.find('router-link').vm.$attrs.to === 'helloworld';
    console.log('foobar', foo, bar);
  });
});

First issue was that the slots do not accept text, only components, which need a root element.

Next, the shallow wrapper can't mount the component, seemingly it cant find router-link.

 FAIL  test\unit\specs\GoHome.spec.js
  ● Console

    console.error node_modules\vue\dist\vue.runtime.c
ommon.js:477
      [Vue warn]: Unknown custom element: <router-lin
k> - did you register the component correctly? For re
cursive components, make sure to provide the "name" o
ption.

      (found in <Root>)

  ● GoHome.vue › displays default message

    [vue-test-utils]: wrapper.hasProp() must be calle
d on a Vue instance

      at throwError (node_modules/vue-test-utils/dist
/vue-test-utils.js:12:9)
      at Wrapper.hasProp (node_modules/vue-test-utils
/dist/vue-test-utils.js:605:5)
      at Object.<anonymous> (test/unit/specs/GoHome.s
pec.js:12:43)
          at Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/
index.js:42:16)
          at <anonymous>
      at process._tickCallback (internal/process/next
_tick.js:188:7)

I'm not sure if I'm calling wrapper correctly or not, or if wrapper.find is wrong. Does anyone have some examples on testing a component with router-link.

I'm using vue-test-utils 1.0.0-beta.1

from vue-test-utils.

eddyerburgh avatar eddyerburgh commented on September 26, 2024

Sorry, the example in my original post is wrong. I've updated it. If you're still having issues, can you ask a question on stubbing router-link on StackOverflow.

from vue-test-utils.

yoerriwalstra avatar yoerriwalstra commented on September 26, 2024

@eddyerburgh I know I'm late to the discussion, but I believe the method for testing if a stubbed component has been passed the correct prop deserves a small recap. Do you agree with my implementation to test the value of a to prop on a router-link element?

import { shallowMount, RouterLinkStub } from '@vue/test-utils';
import ButtonLink from '@/components/ButtonLink.vue';

describe('ButtonLink.vue', () => {
  const to = '/companies';
  const wrapper = shallowMount(ButtonLink, {
    stubs: { RouterLink: RouterLinkStub },
    propsData: { to },
  });

  it('use route provided in props.to as href', () => {
    // If you stub a component, the stub copies component props to the stub.
    // This means you can check a stubbed component is passed the correct prop
    const href = wrapper.find(RouterLinkStub).props('to');
    expect(to).toEqual(href);
  });

from vue-test-utils.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.