Making it work with vitest? #184
-
I have specific need to write tests that would use real router. However, if I use Here is how the router file is setup: import {
createRouter,
createWebHistory,
type RouteRecordRaw
} from "vue-router/auto"
import { setupLayouts } from "virtual:generated-layouts"
import "./axios" // Configure axios interceptors
const router = createRouter({
extendRoutes(routes) {
// Apply layouts to each route
return routes.map((route) => {
return recursiveLayouts(route)
})
},
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { top: 0 }
}
},
history: createWebHistory()
})
const recursiveLayouts = (route: RouteRecordRaw): RouteRecordRaw => {
if (route.children) {
for (let i = 0; i < route.children.length; i++) {
// eslint-disable-next-line security/detect-object-injection
route.children[i] = recursiveLayouts(route.children[i])
}
return route
}
return setupLayouts([route])[0]
} I use it in tests like so: import router from "@/router"
describe("Test, () => {
const mountOptions = {
global: {
plugins: [router]
}
}
test("test something", async () => {
const wrapper = mount(App, mountOptions)
expect(true).toBe(true)
})
}) Main TS config file: {
"extends": "./tsconfig.common.json",
"compilerOptions": {
"composite": true,
"sourceMap": false,
"allowSyntheticDefaultImports": true,
"useDefineForClassFields": true,
"lib": ["ESNext", "DOM", "DOM.Iterable"],
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.vue",
"src/*.vue",
"src/*.ts",
"src/i18n/*.json",
"auto-imports.d.ts",
"typed-router.d.ts",
"tests/**/*.ts",
],
"exclude": ["node_modules", "dist", "public"]
} Any ideas how to make it work? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
You probably need to tell vitest to also use the plugin. I don't think unplugin-vue-router is doing anything in particular to break its compatibility with vitest. BTW the router is a stateful object, so it's recommended to create one per test |
Beta Was this translation helpful? Give feedback.
-
@posva after further testing it turns out that the incompatibility is with It works fine with v0.31.4, so it means that only the latest update (as of now) to However, I don't have enough time to determine if this is an issue with this plugin or vitest itself. |
Beta Was this translation helpful? Give feedback.
-
To resolve this you can either copy your entire 'plugins' definition from vite.config.ts to vitest.config.ts, or better, just copy the 'test' key from vitest.config.ts to your vite.config.ts and then delete your vitest.config.ts. Both of these resolved the problem for me. |
Beta Was this translation helpful? Give feedback.
Upgrading to
vitest
v0.32.2 did the trick for me eventually.