testing-library / vue-testing-library

🦎 Simple and complete Vue.js testing utilities that encourage good testing practices.
http://testing-library.com/vue
MIT License
1.07k stars 111 forks source link

Cannot manually set route parameters on Vue-Testing-Library@next using useRoute() #218

Closed kerryboyko closed 3 years ago

kerryboyko commented 3 years ago

I'm not sure if this is a bug report or just incomplete documentation.

We're using Vue-Testing-Library @ next (as of 10 Apr 2021) and trying to test a component that uses useRoute() to get a route parameter, 'hash'. It's for our login page; specifically, the "ResetPassword.vue" component.

In this component, the user arrives to the page via a link they have recieved in their e-mail, (so there is no component on the page to click) which contains a unique hash (so that people can't change other people's passwords willy nilly.)

The component accesses this hash in the setup via useRoute(), i.e,

setup(){
  const route = useRoute();
  const {hash} = route.params; 
}

Using Vue2 syntax, we were able to just pass in 'hash' as a prop during the testing suite - as both this.$route.params.hash and any prop named 'hash' would both resolve to 'this.hash', it worked. This is no longer working with useRoute().

In the render function in the test suite, we are declaring the function like this:

  beforeEach(() => {
    wrapper = render(ResetPassword, {
      global: {
        plugins: [mainRouter], //mainRouter is the router defined,
      },
    });
  });

It should be noted that we tried passing in the callback function to try to set the route as such, but Typescript complains that 'render' takes only 1-2 parameters. Using //@ts-ignore and passing in the callback function does nothing... so this doesn't work and in fact has no effect.

  beforeEach(() => {
    wrapper = render(ResetPassword, {
      global: {
        plugins: [mainRouter], //mainRouter is the router defined,
      },
      // @ts-ignore
      (_vue: any, _store: any, router: any) => {
        router.push('/path/to/This-Is-The-Hash')
      }
    });
  });
afontcu commented 3 years ago

Hi!

we tried passing in the callback function to try to set the route as such

This won't work, as VTL for Vue 3 removed the callback parameter.

Even if not ideal, could you try if setting a mock works?

render(ResetPassword, {
  global: {
    plugins: [mainRouter], //mainRouter is the router defined,
    mocks: {
      $route: {
        params: { username }
      }
    }
  },
})
lmiller1990 commented 3 years ago

A bit late, but mocks will only work for values on the Vue prototype.

I'm finding this library to be useful for testing with Vue Router.