I'm trying to understand the logic of mocking the Vue-Router with Vitest.
For this, I tried to set up and mock my test environment on a very simple project. When I tried to proceed according to the official documentation of Vue-Test-Utils, I always got an error. I don't know if it's because they use Jest.
Using real vue-router solves my problem but I think it's better to mock vue-router.
Below, I first convey the source codes of the project, and then the error I received.
Home.vue
<script setup lang="ts">
import {onMounted} from "vue";
import {useRoute} from "vue-router";
const route = useRoute()
onMounted(() => {
console.log(route.query)
})
</script>
<template>
<div>Home</div>
</template>
Home.spec.ts
import {expect, it, vi} from "vitest";
import {mount} from "@vue/test-utils";
import Home from "../src/components/Home.vue"
it('Home Test', async () => {
const wrapper = mount(Home)
expect(wrapper.exists()).toBeTruthy()
})
vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
test: {
environment: 'jsdom',
include: ['./test/**/*.spec.ts'],
exclude: ['node_modules', 'dist'],
globals: true
}
})
My error message is as follows:..
Methods I've Tried
I tried to mock vue-router like below
vi.mock('vue-router', () => ({
useRoute: vi.fn(),
}))
or just
vi.mock('vue-router')
Here is my final Home.spec.ts file
import {expect, it, vi} from "vitest";
import {mount} from "@vue/test-utils";
import Home from "../src/components/Home.vue"
vi.mock('vue-router')
it('Home Test', async () => {
const wrapper = mount(Home, {
global: {
stubs: ["router-link", "router-view"]
}
})
expect(wrapper.exists()).toBeTruthy()
})