Encountered an issue while trying to set up mocks with $route in vue-test-utils

I am currently practicing test referencing by using a mock router. Here is the code I am working with:

NestedRoute.vue

<template>
<div>
    <div>Nested Route</div>
    <div class="username">
        {{ $route.params.username }}
    </div>
</div>
</template>

<script>
export default {

}
</script>

<style>

</style>

router.js

import Vue from 'vue'
import Router from 'vue-router'

import Home from './views/Home.vue';
import NestedRoute from './views/NestedRoute.vue';

Vue.use(Router)

export const routes = [
  { path: '/', name: 'home', component: Home },
  { path: '/nested-route', name: 'nroute', component: NestedRoute }
];

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

test.spec.js

import NestedRoute from '@/views/NestedRoute.vue';
import VueRouter from 'vue-router';
import {routes} from '@/router.js'

const localVue = createLocalVue();
localVue.use(VueRouter);

describe('NestedRoute', () => {
        it('renders a username from query string', () => {
            const username = 'tom';
            const $route = {
                params: { username }
            };

            const wrapper = mount(NestedRoute, {
                mocks: {
                    $route
                }
            });

            expect(wrapper.find('.username').text()).toBe(username);
        });
});

Upon running the test, I encountered the error

[vue-test-utils]: could not overwrite property $route, this is usually caused by a plugin that has added the property as a read-only value
.

I attempted to refer to an issue regarding 'Cannot use mocks with localVue', however, I was unable to resolve my problem. How can I effectively use a mock to utilize $route?

Answer №1

import { mount, createLocalVue } from '@vue/test-utils'
import MyComponent from '.../../MyComponent'

describe('MyComponent', () => {
  let wrapper

  beforeEach(() => {
    const localVue = createLocalVue()
    wrapper = mount(MyComponent, {
      localVue,
      mocks: {
        $route: {
          params: {
            id: 200000
          }
        }
      }
    })
  })

  it('has $route set', () => {

  })
})

This method has proven to be effective for me.

The key difference lies in excluding the import of routes from router.js. Somehow, importing routes used in Router from router.js in test.spec.js interferes with the process of localVue by introducing the global router's routes into the test, thus contaminating the localVue instance being tested.

To address this issue, simply remove

import {routes} from '@/router.js'

from the test.spec.js file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize clipboard functionality in automated tests while using Selenium WebDriver in conjunction with JavaScript

How can I allow clipboard permission popups in automated tests using Selenium web driver, Javascript, and grunt? https://i.stack.imgur.com/rvIag.png The --enable-clipboard and --enable-clipboard-features arguments in the code below do not seem to have an ...

React does not trigger a re-render when dynamically generated buttons are created

I am encountering an issue with displaying social media buttons on my website. I have implemented a tweet button and a Facebook like button to appear on every page, but they only load correctly on the initial page visit. Upon navigating to another page and ...

Utilizing Axios for Submitting Form Data: A Step-by-Step Guide

Currently, I am in the process of developing a project that consists of a springboot backend and Vue frontend. At this point, I have successfully managed to retrieve a list of products from my database using GET requests. While I can display this list on a ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...

Converting SQL database tables into MVC webpages using JavaScript

Currently, I am working on populating an MVC webpage by utilizing a Controller and a View using C#, HTML, and Javascript exclusively. It is crucial that I avoid using a model or PHP due to the existing format in use. Thus far, all the data has been succes ...

Utilizing Vue.js to set the instance global property as the default value for a component prop

Is it possible to access a global property from my vue instance when setting a default prop value in my component? This is what I would like to achieve props: { id: { type: String, default: this.$utils.uuid } } I attempted to use an arrow fun ...

Is there a way to update the dictionary in the context processor without having to reload the page?

I have implemented a custom context processor that returns the value of "unread_messages_count". However, when I try to update this value on the template using the following JavaScript: var update_message_count = setInterval(function(){ ...

Is it a breach of separation of concerns to validate using ng-pattern?

I have a requirement in Singapore to validate contact numbers entered by users. The number must start with 6, 8, or 9 and should have a total of 8 digits. I am currently utilizing ng-pattern on an input field with a regex solution, but I am concerned abo ...

Using a render target causes certain elements of my visual graphics to become hidden

Hey there, I've been experimenting with render targets lately and encountered some issues. I've put together a simplified example below: init = function() { // RENDERER canvas = document.getElementById("mycanvas"); renderer = new THREE ...

A guide on organizing an array of objects by a specific property using a separate array

Here is the array I am working with: var arr = [ { count: 27, dataRil: "08/06/21", subCateg: "FISH", }, { count: 22, dataRil: "08/06/21", subCateg: "DOG", }, { count: 28, dat ...

The Functionality of Accordions

I have created a responsive accordion script that functions smoothly and allows for easy access to content within each drawer. Unlike many accordions, this one does not cause issues with positioning after opening. The code I am using includes a toggle acti ...

What is the best way to invoke the first exported function from the second exported function?

I am looking to create a file containing four or five exported functions. exports.firstFunction = function() { // some code }; exports.secondFunction = function() { // need to call firstFunction }; My issue is that I want the second expo ...

Tips for resolving the React Hook Type Error issue

Error Image const isLoggedIn = true; const handleChangeEvent = () => {}; const [displayPassword, setDisplayPassword] = useState(false); const handleTogglePassword = () => setDisplayPassword((prevDisplayPassword) => !prevDi ...

Copy the click function to a contenteditable <div> with spellcheck feature

When using a contenteditable <div> in Chrome, the native spell check feature will only work if the user manually clicks into the <div>. But what if you want to add a contenteditable <div> dynamically? Is there a way to trigger the spell c ...

What is the method for transmitting a concealed attribute "dragable" to my component?

Currently, I have successfully integrated a here map into my project, but I am now tackling the challenge of adding draggable markers to this map. To achieve this, I am utilizing a custom package/module developed by my company. This package is designed to ...

What is the most effective way to inform the user when the nodeJS server can be accessed through socketIO?

I have developed a web app that indicates to the user when the server is online for data submission. Although the current code functions properly for single-user interaction, I am facing an issue where one user's connection or disconnection directly i ...

Showing button based on a particular value

I am trying to dynamically display a button based on the value of the sendSMS property for the logged-in user. I have added this property in the viewer model, which is connected to the user's base model. However, I am encountering difficulties with us ...

NodeJS MySQL failing to retrieve the most updated data post-write

I'm struggling to solve an issue where after performing data operations (create, update, delete) and then querying for the data afterwards, I receive the previous version of the data rather than the updated version. For example: Let's say I hav ...

Is it possible to retrieve the current CSS value set by a media query using JavaScript?

Currently working on a website project that involves accessing and manipulating the display property of a menu. The goal is to toggle the menu open or closed based on its current state. In my setup, the initial state of the menu is defined as closed using ...

why is my angular listing malfunctioning when I try to compare two fields?

<div ng-controller="SamsungServicesCtrl"> <ion-content> <li class="item item-checkbox" ng-repeat="item in items" > <img src="{{item.icon}}" style="float:left;height:30px;width:30px;padding-right:5px;" & ...