Search code examples
vue.jsvuejs3vue-routervue-test-utilsvitest

How to mock the route object in Vue 3 composition?


I'd like to mock the route object to prevent test failures like TypeError: Cannot read properties of undefined when accessing route.x.

I tried:

const route = { fullPath: '/', path: '/' };

const options = {
  mocks: {
    route,
  },
};

Solution

  • Since the route object is no longer a global object you have to do the following:

    const route = { fullPath: '/', path: '/' };
    
    vi.mock('vue-router', () => ({
      useRoute: () => route,
    }));