Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i solve route.params is undefined?

i have this part in my code, i want to test, but when i run the test route.params sound like the wrong:

 onMounted(async () => {
        try {
          const { tokenId } = route.params

it i used to get the id from url, but at the moment to test it

i am getting this error Error TypeError: Cannot read property 'params' of undefined

this is my test:

beforeEach(() => {
  wrapper = shallowMount(App, {
    mocks: {
      route: {
          params: {
            id: 'id'
          }
        }
    },
    global: {
      plugins: [store],
    },
    computed: { notFound: () => {} },
  })
})
like image 645
signup Avatar asked Oct 20 '25 05:10

signup


1 Answers

Your mocks.route does not mock

import { useRoute } from 'vue-router'
//...

setup() {
  const route = useRoute();
  //...
}

You might want to have a look at examples presented here for a detailed approach on how to test various router related scenarios with a vue3 composition api setup.


To simply make your component not fail when useRoute() returns undefined, you could use this:

const { tokenId } = route?.params || {};
if (tokenId) {
  // do your thing...
}

There's no need for try.


To test that your component does what it's supposed to based on tokenId route param value, then you should mock vue-router in your test, to return a function returning a params object:

This should work:

jest.mock('vue-router', () => ({
  useRoute: () => ({ params: { id: 'id' } })
}));
like image 132
tao Avatar answered Oct 21 '25 20:10

tao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!