Error message stating that VueRouter is not defined during karma unit tests

I'm encountering warnings during the tests on my new Vue.js project. Whenever a component utilizes the router, either in the template as a <router-link> or programmatically as this.$router.push('/');

The tests are passing but these warnings are being logged:

ERROR LOG: '[Vue warn]: Error in render: "TypeError: Cannot read property 'resolve' of undefined"

found in

---> <RouterLink>
   <Root>'

I am using Vue2 and the project is based on the webpack project generated by the cli tool.

My unit test index.js:

import Vue from 'vue';
import VueNativeSock from 'vue-native-websocket';
import Router from 'vue-router';

Vue.use(Router);
Vue.use(VueNativeSock, process.env.WEBSOCKET_ADDR, { format: 'json', reconnection: true });
Vue.config.productionTip = false;

const testsContext = require.context('./specs', true, /\.spec$/);
testsContext.keys().forEach(testsContext);

const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/);
srcContext.keys().forEach(srcContext);

My main.js:

import Vue from 'vue';
import VueNativeSock from 'vue-native-websocket';
import VueHead from 'vue-head';
import App from './App';
import router from './router';

Vue.config.productionTip = process.env.NODE_ENV === 'production';
Vue.use(VueNativeSock, process.env.WEBSOCKET_ADDR, { format: 'json', reconnection: true });
Vue.use(VueHead);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
  head: {
    link: [
      { rel: 'icon', href: '/static/favicon-32x32.png', sizes: '32x32', type: 'image/png' },
    ],
  },
});

Could anyone provide insight into how to resolve these warnings?

A simple test example could be like the following:

import Vue from 'vue';
import ViewDTCs from '@/components/ViewDTCs';

describe('ViewDTCs.vue', () => {
  const Constructor = Vue.extend(ViewDTCs);
  const vm = new Constructor().$mount();
  ViewDTCs.$socket = new WebSocket(process.env.WEBSOCKET_ADDR);
  it('has a created hook', () => {
    expect(typeof ViewDTCs.created).to.equal('function');
  });
  it('should render page', () => {
    expect(vm.$el.textContent).to.contain('Retrieving DTCs');
  });
});

Answer №1

It seems that your route configurations may not be properly set up in your testing environment. If you are using Karma along with Avoriaz or Vue Test Utils, you can test components with routes like this:

import { mount } from 'vue-test-utils'
import router from 'src/router' // path to your router
import MyComponent from 'src/components/MyComponent'

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

  beforeEach(() => {
    wrapper = mount(MyComponent, {
      router: router
    })
  })

  it('has a created hook', () => {
    expect(typeof wrapper.created).to.equal('function')
  })
  ...
})

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

Creating an inline function in JavaScript for an anchor tag

I'm attempting to open a new window with a specific URL while also sharing the current page's address through an inline function. Here's what I have so far: a href="javascript:void(0);" onClick='(function() { var link = string.conc ...

Scroll a div using JavaScript/jQuery

I'm currently facing some challenges in resolving this issue. My goal is to pan a DIV using jQuery. The process is quite straightforward - on mouseDown, I capture X & Y coordinates and then subtract them from the newly obtained X & Y values during mou ...

Determine the class name of an element when it is clicked on

For various reasons, I am unable to use $('.class').click or on('click', function..) Therefore, I must utilize the onclick="" event from the html element. Is there a way to determine the class of the element where the onclick event oc ...

Empty input fields in Javascript calculations will result in a NaN output

I need to perform a calculation using values entered into form fields and JavaScript. The formula I'll be using is as follows: totalEarnings = income1 + income2 * 0.7 + income3 / 48 + (income4 * 0.7) / 48; The variables income1, income2, income3, an ...

Having trouble with TypeScript Library/SDK after installing my custom package, as the types are not being recognized

I have created my own typescript library using the typescript-starter tool found at . Here is how I structured the types folder: https://i.stack.imgur.com/igAuj.png After installing this package, I attempted a function or service call as depicted in the ...

Tips on downloading an image using the URL in nestjs

I'm trying to retrieve a link and save the associated image in the static folder, but I seem to be encountering some issues with my code. Here's what I have so far: @Injectable() export class FilesService { createFileFromUrl(url: string) { t ...

[VUE WARNING]: The prop "Items" failed type check. It was supposed to be an array but instead received a Promise

I am completely new to the world of node technology and I am challenging myself with a project to enhance my skills. So far, I have seen some success (perhaps by luck), but now I seem to be stuck. The client side involves 'axios, vue, vue-router, vuet ...

Results not showing up

After attempting to incorporate the scores into a table, I am facing an issue where they are not displaying. Can anyone offer assistance with this problem? I am currently hosting on GitHub Pages. File: https://raw.githubusercontent.com/Eternal-Network/Ete ...

Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry: jQuery check if image is loaded I find myself in a scenario where the following HTML structure is utilized: <div class="image"> <img class="" src="content-images/1.jpg"> <span class="slide" rel="content-images/ ...

Enter information into the TextArea and jQuery dialog

I require assistance in populating a textarea with data obtained from querying a database. I have a jQuery dialog that contains another dialog, inside of which is a textarea. Here is some pseudocode: <MODAL> <modalB> <TextArea>s ...

Make sure to attach a resize event handler just once

I am working with a widget that inserts a div element into the DOM. This div requires some JavaScript to handle the resize event effectively. Here's the issue: The widget may be added multiple times on the same page, but I want to avoid adding re ...

Dealing with errors when working with cross-domain JSONP requests in jQuery can be a

My attempts to capture a bad request error using my jquery code have been unsuccessful. $.get('http://example.com/', {}, function () {}, 'jsonp') .done(function () { // never fires }) .fail(function () { // never fires }) .a ...

delayedExecution function

I have been extensively researching my issue and want to avoid posting a duplicate question. Despite trying the methods suggested in my research, I am unable to get my function to delay as intended! Could someone please review my syntax and help me identi ...

Guide to showcase Material UI drawer with a margin at the top

I'm having trouble implementing a Material UI drawer with some top margin instead of starting from the very top of the page. I've tried applying the marginTop property, but it's not working. You can view my code on CodeSandbox here: Drawer. ...

What are the signs of a syntax error in a jQuery event like the one shown below?

One of my forms has an ID attribute of id ='login-form' $('#login-form').submit(function(evt) { $('#login-button').addClass('disabled').val('Please wait...'); evt.preventDefault(); var postData = ...

"Node.js mystery: Why does a function call return undefined, only to be evaluated

Utilizing the async module, I am running a series of functions in parallel. However, I have encountered an issue where the return value of another function is undefined because the callback does not wait for it to be evaluated. function getGenresId(genres ...

Error encountered while attempting to save user to mongoose due to bcrypt issue

I am currently dedicated to expanding my knowledge in node and react through a tutorial. If you want to check out the repository, here is the link: https://bitbucket.org/grtn/cloudstruct/src/develop/ While making a post request to /api/users/register, I ...

Tips for implementing a handler on a DOM element

$(document).ready(function(){ var ColorBars = document.getElementsByClassName("color-bar"); var number = 0; ColorBars[0].onclick = hideLine(0); function hideLine(index){ var charts = $("#line-container").highcharts(); v ...

Building a Div Tag Layout with CSS for Full Width and Left Position of 300px

Experiencing some trouble with styling a div element. My goal is to have the div start at left:300px and stretch across the entire width of the browser window. However, when I apply width:100%, the div extends beyond the boundaries of the browser screen. ...

Ways to halt a script entirely once its tag has been eliminated

I have a script from a page tracker website that runs periodically. Occasionally I need to restart the script from the beginning. To do this, I typically remove the script tag from the DOM and then re-append it. However, because the script utilizes setInt ...