Troubleshooting problem with Vue JS component template rendering during testing

Currently, I am facing some challenges with testing a Vue component. The code below functions correctly, but when it comes to testing, I encounter issues. After conducting some research, I discovered that Vue 2.0 only uses the runtime-only build when importing Vue, and in order to resolve this, I either need to utilize vue/esm or employ the render function. However, my dilemma lies in the fact that I am not utilizing webpack or any build system (using tsconfig) to create an alias.

I attempted using template:'', but it still throws errors. When I tried using the render/createElement function, I found difficulty incorporating my own HTML file/template as it appears to only aim at creating a new element rather than injecting a template.

ERROR: '[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

COMPONENT:

import {
    debounce
}
from 'npmPackage/debounce';
import Vue from 'vue';
import Component from 'vue-class-component';
import './navigation-bar.styles.less';
import {
    menuItemList,
    secondaryButton
}
from './types';

 @ Component({
    props: ['panels', 'secondaryButton'],
    // render: (createElement) => { return createElement('div', require('./navigation-bar.html')); }
    template: require('./navigation-bar.html')
})

export class NavigationBar extends Vue {
    public menuActive: boolean = false;
    public menuClass: string = '';
    public panels: menuItemList;
    public secondaryButton: secondaryButton;

    private animateMenu: () => void = debounce(this.toggleMenuClass, 300, true);

    public toggleMenu(): void {
        this.animateMenu();
    }

    private toggleMenuClass(): void {
        this.menuActive = !this.menuActive;
        this.menuClass = this.menuActive ? 'show' : 'hide';
    }
}

Vue.component('navigation-bar', NavigationBar);

UNIT TEST:

import {
    expect
}
from 'chai';
import {
    spy,
    stub
}
from 'sinon';
import Vue from 'vue';
import {
    NavigationBar
}
from '../src/navigation-bar.component'
import {
    IMenuItem
}
from "../src/types";

describe('Navigation bar component', () => {
    let panels: Array < IMenuItem > ;
    let navigationBar: NavigationBar;

    beforeEach(() => {
        panels = [{
                label: 'my-account',
                action: function () {}
            }, {
                label: 'home',
                action: stub
            }
        ];
        navigationBar = new NavigationBar();
        navigationBar.$mount();
    });

    describe('Checks that only one action is being called per panel', () => {
        it('checks actions are called', () => {
            console.log(navigationBar.$el);
            navigationBar.panels = panels;
            const menuItem = navigationBar.$el.querySelectorAll('.menu-item');
            menuItem.length.should.equal(panels.length);

            const menuItem1 = menuItem[0];
            menuItem1.should.be.instanceOf(HTMLElement);
            const html = menuItem1 as HTMLElement;
            html.click();
            panels[0].action.should.have.been.calledOnce;
            panels[1].action.should.not.have.been.called;
        });
    });
});

Answer №1

To optimize your website's performance, consider using the CDN version of Vue.js instead of the npm package.

Another option is to incorporate Vue directly from import Vue from vue/dist/vue.js

https://i.sstatic.net/EcrRP.png

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

Ruby on Rails allows for the selection of values in a dropdown menu to trigger the visibility of different sections of HTML

As a newcomer to Rails, I was able to successfully implement the onclick function for a f.checkbox element. Now, my challenge lies in achieving a similar functionality for a f.select element within a _form. Below is the code snippet that works for a chec ...

Is there a way to modify the color of a selected tile within a treemap displayed in highcharts when using react?

I'm using a Tree map chart from the High-chart library, but I'm encountering an issue with changing the color of the active tile or the tile that was clicked. I attempted to update the color of the clicked tile on my end, but it didn't work ...

What could be causing the issue with dayjs dynamic importing in TypeScript?

Currently, I am developing a web screen within a .NET application and facing an issue with sending datetime preferences from the system to the web screen using CefSharp settings. AcceptLanguageList = CultureInfo.CurrentUICulture.Name In my TypeScript code ...

What is the best way to loop through values in a complex JSON structure?

After retrieving data from the "Orders" collection in Firebase Firestore, I am facing an issue with fetching a specific value from the object. The code for fetching data from Firebase is as follows: app.get('/trial',(req,res)=>{ const orders ...

Encountering issues during the installation of node-sass

After attempting to install node-sass for my React project, I encountered the following error. Despite trying numerous solutions, such as reinstalling and starting a new project from scratch, I have been unable to resolve this issue. I made sure to updat ...

When using React Final Form, the onBlur event can sometimes hinder the

What is the reason that validation does not work when an onBlur event is added, as shown in the example below? <Field name="firstName" validate={required}> {({ input, meta }) => ( <div> <label>First Name</label& ...

Struggling to get my React web app up and running without using npm start. Any help would be greatly appreciated

I'm having trouble getting my create-react-app to function properly without using npm start. Can someone provide guidance on what steps I should take? ...

Is it necessary to store tokens in cookies, local storage, or sessions?

I am currently utilizing React SPA, Express, Express-session, Passport, and JWT. I find myself puzzled by the various client-side storage options available for storing tokens: Cookies, Session, and JWT/Passport. Is it necessary to store tokens in cookies, ...

tips for incorporating jade Mixin in JavaScript

Experimenting with test mixins in jade language mixin test(testName) #test span Test String Desire to incorporate this functionality into javascript (as declared in the jade file) script(type='text/javascript'). $( document ).on( "cli ...

Efficient File Upload Feature Compatible with all Browsers, Including Internet Explorer versions 7, 8, and 9

Can someone assist me with a problem I'm facing? I need a code script that enables multiple file uploading on all browsers. While HTML5 supports Chrome and Mozilla Firefox, it does not support IE. I am looking for a script/jquery solution that works ...

Setting up proxy settings for GIT and NPM on Windows 10

Does anyone know the steps to set up the corporate proxy URL for GIT and NPM packages on Windows 10? I can't seem to find the .gitconfig or .npmrc files in the Users folder. ...

Ways to transform an ISO string formatted date time into the following hour

I have a function that converts my date to RFC3339 format, but I want it to be converted to the upper time limit. Could someone please help me figure out how to convert it to the upper limit? const date = new Date(); // converting to RFC 3339 format ...

Issues with JavaScript functionality arise when a modal is loaded using AJAX and TWIG

I'm experiencing an issue with my Javascript. I've created a Javascript modal function that uses AJAX to retrieve content, and then the innerHTML function places that content into the modal. While the modal displays the content correctly, the Jav ...

During the resolution process: @typegoose/[email protected] npm ERR! Discovered: [email protected] in the mongoose node_modules folder

I am new to connecting microservices and attempting to link the project backend-common with another project. Here is my process: npm link npm link mongoose However, when I try to link mongoose, I encounter an error: npm ERR! ERESOLVE could not resolve np ...

The axios library fails to send formdata to the server

Recently, I've been working on an axios code to handle form data submission. Here's the snippet of the code: updatesetting: function(){ let formData = new FormData(); formData.append('email', this.email); formData.append(&a ...

Steer clear of directly accessing views in AngularJS using angular-ui-router

In my AngularJS App setup, I have the following configuration: angular .module('MyApp') .config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvi ...

Tips on emphasizing all div elements and incorporating navigation to each of them

I am seeking a method to enhance a div with highlighting when there is a click or mouseover event. For instance, changing or adding a border color using JavaScript on click or mouseover is straightforward. Recently, I have been contemplating the idea of a ...

One laptop is experiencing unusually sluggish JavaScript performance compared to the rest of the devices in the group

Currently, I am developing a web application that heavily relies on JavaScript. While most computers (all running IE6 unfortunately) have an average document.ready time of about 2 seconds, there is one computer experiencing extremely slow JavaScript execut ...

Hyperlinks springing to life on mouseover

After spending countless hours tweaking my CSS code, I've hit a roadblock and need some assistance. My issue lies with the links on hover that seem to be jumping unexpectedly. The goal was to create a mobile-responsive hamburger menu that transforms i ...

Node 15 (which is not a long-term support version) can cause issues when trying to run `npm install` with the package "@angular-devkit/build-angular" at version "~0.1000.0

Encountering issue with npm install due to dependency ""@angular-devkit/build-angular" : here is a snippet from the package.json file { "name": "myApp", "version": "0.0.1", "devDependencies&quo ...