I have a Vitest like the following
import { createWebHistory, createRouter } from "vue-router";
import Home from "../components/Home.vue";
import Other from "../components/Other.vue";
const routes = [
{ path: '/', component: Home },
{ path:"/other", component: Other}
]
const router = createRouter({
history: createWebHistory(),
routes,
})
export {router as mainRoutes};
<template>
<div class="wrapper">
<div class="links">
<router-link to="/">Go to Home</router-link>
<router-link class="other" to="/Other">Go to elsewhere</router-link>
</div>
<router-view></router-view>
</div>
</template>
<script setup>
</script>
<style scoped>
.links{
display:flex;
}
.wrapper{
display:flex;
flex-direction: column;
}
</style>
import { describe, it, beforeAll } from 'vitest';
import { mount } from '@vue/test-utils';
import {mainRoutes} from "../src/router/index.mjs";
import App from "../src/App.vue";
describe("App", ()=>{
expect(App).toBeTruthy()
let wrapper;
beforeAll(async ()=>{
await mainRoutes.push('/')
await mainRoutes.isReady()
wrapper = mount(App, {
global: {
plugins: [mainRoutes]
}
});
})
it("Simple Click Test", async ()=>{
await wrapper.find('.other').trigger('click');
console.log(wrapper.html());
expect(wrapper.html()).toContain('I Think you should be somewhere else');
})
})
But when I run with vitest run --coverage
I get...
[Vue Router warn]: history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:
history.replaceState(history.state, '', url)
You can find more information at https://next.router.vuejs.org/guide/migration/#usage-of-history-state.
and the click doesn't seem to work because the test fails and the console log shows the old value.
I also tried adding await mainRoutes.isReady()
after the click but that didn't help either.
This all does seem to match the docs
How do I get a router-link click to update the router-view?
I can confirm that it works this way...
// await wrapper.find('.other').trigger('click');
await mainRoutes.push('/other')
await mainRoutes.isReady()
console.log(wrapper.html());
expect(wrapper.html()).toContain('I Think you should be somewhere else');
But I still get the warning and can't get it to work with the click
Ok, i figured it out for my case. The solution for me was to use createMemoryHistory
instead of createWebHistory
in the tests. Because i am in node environment and not in browser environment. Maybe this is also helpful for you or others
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With